问题描述
我在多对多关系中有以下两个2个模型:
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');
}
}
和
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);
但是,执行完最后一条语句后,出现以下错误: exception 'BadMethodCallException' with message 'Method sync does not exist.
'我也为attach
遇到了相同的错误.另外,我不确定是否应该在中间表permission_role
的位置提供名称?谢谢.
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.
推荐答案
您需要使用以下内容:
$role->permissions()->sync($permissions);
别忘了()
更多说明:
$role->permissions
是Collection实例.
$role->permissions
is a Collection instance.
$role->permissions()
是包含sync()
方法
这篇关于保存多对多关系,不存在同步/附加吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!