保存多对多关系,sync/attach不存在?

Saving many-to-many relationship, sync/attach doesn't exist?

我在多对多关系中有两个以下 2 个模型:

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');
    }

}

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');
    }
}

我在这里要做的是创建一个可以创建新角色的页面,并将该角色与已创建的权限相关联:

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

在控制器中,我尝试从页面中提取选定的权限并保存所有内容:

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

然而,在执行最后一条语句后,出现以下错误: exception 'BadMethodCallException' with message 'Method sync does not exist.' attach 我也得到同样的错误。另外,我不确定我是否应该在某处提供中间 table permission_role 的名称?谢谢。

您需要使用以下内容:

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

别忘了 ()

编辑:更多解释:

$role->permissions 是一个 Collection 实例。

$role->permissions() 是一个 belongsToMany 实例,其中包含 sync() 方法