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

Asked

Viewed 278 times

2

I have two models that are linked, through the belongsToMany, a relationship table N:N.

So the structure is arranged as follows:

Diagrama EER

class Permissao extends Eloquent{
   public function niveis()
   {
       return $this->belongsToMany('Nivel', 'niveis_permissoes');
   }
}


class Nivel extends Permissao
{
   public function permissoes()
   {
         return $this->belongsToMany('Permissao', 'niveis_permissoes')
                     ->withPivot('prioridade');
   }
}

In this scenario, I need to update the "priority" field that is in the table nivel_id and permissao_id informed.

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

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

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

However, I don’t want to bring this data, but I just want to update it directly through the returned object when we built the query by Eloquent(which is the class Illuminate\Database\Eloquent\Builder), as is usually done in a data update-only operation.

Behold:

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

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

1 answer

3


Guys, I ended up discovering, by "navigating" the source code of the class Illuminate\Database\Eloquent\Relations\BelongsToMany.

There, there is a method called updateExistingPivot.

Example:

Nivel::findOrFail($nivelID)
->permissoes()
->updateExistingPivot($permissaoID, ['prioridade' => 5]);
  • I don’t understand where the permit came from, it’s an eloquent pattern ?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.