How to update the pivot in LARAVEL 4 using the UPDATE method?

2

I have two Models that are linked, through belongsToMany , to a relationship table N: N.

So the structure is arranged as follows:

classPermissaoextendsEloquent{publicfunctionniveis(){return$this->belongsToMany('Nivel','niveis_permissoes');}}classNivelextendsPermissao{publicfunctionpermissoes(){return$this->belongsToMany('Permissao','niveis_permissoes')->withPivot('prioridade');}}

Inthisscenario,Ineedtoupdatethe"priority" field that is in the table levels_permissions, according to nivel_id and permissao_id reported.

I was able to update the data, bringing the result first, and then using the save method, pivot .

$pivot = Nivel::findOrFail($nivelID)
                ->permissoes()
                ->whereId($permissaoID)
                ->first()->pivot;

$pivot->fill(['prioridade' => $prioridade])->save();

However, I do not want to bring this data, but I want to simply update it directly through the returned object when we construct the query by Eloquent (which is the Illuminate\Database\Eloquent\Builder class), as is usually done in an update only operation of data.

See:

$isUpdated = Permissao::where('url', 'like', 'usuario%')
                   ->update(['status' =>' 0]);

Even if the first update example (via save method) already worked, how could I use the Illuminate\Database\Eloquent\Builder::update() method to update a field of this table niveis_permissoes , in the same way I did with save ?!

    
asked by anonymous 10.06.2015 / 14:29

1 answer

3

I ended up finding out by "navigating" through the source code of the Illuminate\Database\Eloquent\Relations\BelongsToMany class.

There is a method called updateExistingPivot .

Example:

Nivel::findOrFail($nivelID)
->permissoes()
->updateExistingPivot($permissaoID, ['prioridade' => 5]);
    
10.06.2015 / 14:56