How to delete all records from a belongsToMany

1

In laravel, when we have a many-to-many relationship, we have a method called attach and detach

The attach adds entry in a n:n relationship, and detach removes them.

In both cases, these operations are performed when passing an array as a parameter

So:

class Action extends Eloquent{

   public function roles()
   {
      return $this->belongsToMany('Role', 'roles_actions');
   }
}


class Role extends Eloquent{

    public function actions()
    {
        return $this->belongsToMany('Action', 'roles_actions');
    }
}

Then, when I want to delete entries from this relationship, I do:

$role = Role::find(1);

$role->actions()->detach([1, 2, 3])
// DELETE FROM roles_actions WHERE action_id IN (1, 2, 3) AND role_id = 1

I would like to know how to delete all entries in this relationship table (without having to specify one by one to do this)

    
asked by anonymous 09.02.2015 / 14:24

1 answer

1

To exclude all relationships, simply execute the detach() method with no parameters:

$role = Role::find(1);

$role->actions()->detach();
    
09.02.2015 / 19:10