我有两个跟随两个模型的多对多关系:
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
的名称?感谢。
答案 0 :(得分:22)
您需要使用以下内容:
$role->permissions()->sync($permissions);
不要忘记()
编辑:更多解释:
$role->permissions
是一个Collection实例。
$role->permissions()
是belongsToMany
个实例,其中包含sync()
方法