保存多对多关系,同步/附加不存在?

时间:2016-03-06 12:40:15

标签: php laravel lumen

我有两个跟随两个模型的多对多关系:

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.&#39; 我也为attach得到了同样的错误。另外,我不确定我是否应该提供中间表permission_role的名称?感谢。

1 个答案:

答案 0 :(得分:22)

您需要使用以下内容:

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

不要忘记()

编辑:更多解释:

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

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