Saving many-to-many relationship, sync/attach does

2020-08-17 06:59发布

问题:

I have two following 2 models in many-to-many relationship :

use Illuminate\Database\Eloquent\Model;

class Permission extends Model
{
    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'permissions';

    /*
    |--------------------------------------------------------------------------
    | Relationship Methods
    |--------------------------------------------------------------------------
    */

    /**
     * many-to-many relationship method
     *
     * @return QueryBuilder
     */
    public function roles()
    {
        return $this->belongsToMany('App\Admin\Role');
    }

}

and

class Role extends Model
{
    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'roles';

    /*
    |--------------------------------------------------------------------------
    | Relationship Methods
    |--------------------------------------------------------------------------
    */

    /**
     * many-to-many relationship method.
     *
     * @return QueryBuilder
     */
    public function users()
    {
        return $this->belongsToMany('App\Admin\User');
    }

    /**
     * many-to-many relationship method.
     *
     * @return QueryBuilder
     */
    public function permissions()
    {
        return $this->belongsToMany('App\Admin\Permission');
    }
}

What I'm trying to do here, is to create a page where new Role can be created, and associate that role with already created Permissions:

@foreach ($permissions as $permission)
                            <label class="checkbox">
                                <input type="checkbox" value="{{ $permission->id }}" name="permissions[]" id="permission_{{ $permission }} }}">
                                {{ $permission->permission_title }}
                            </label>
                        @endforeach

and in the controller I tried this to extract selected permissions from the page and save everything:

// logic to save role
$role->save();
$permissions = Input::get('permissions');
$role->permissions->sync($permissions);

However after the last statement is executed I get the following error: exception 'BadMethodCallException' with message 'Method sync does not exist.' The same error I get for attach as well. Also, I'm not sure if I'm supposed to provide somewhere the name of the intermediate table permission_role ? Thanks.

回答1:

You need to use the following:

$role->permissions()->sync($permissions);

Don't forget the ()

EDIT: Some more explanations:

$role->permissions is a Collection instance.

$role->permissions() is a belongsToMany instance which contains the sync() method