我试图建立一个多对多的关系,在这个例子中是用户和角色。
在用户模型中,我得到了这个:
public function roles()
{
return $this->belongsToMany('App'Role', 'user_role', 'user_id', 'role_id');
}
在角色模型中,我得到了这个:
public function users()
{
return $this->belongsToMany('App'User', 'user_role', 'role_id', 'user_id');
}
我的数据透视表user_role:
public function up()
{
Schema::create('user_role', function(Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->integer('role_id')->unsigned();
$table->timestamps();
$table->foreign('role_id')->references('id')->on('roles');
$table->foreign('user_id')->references('id')->on('users');
});
}
现在,当我执行$user->roles()->attach(1);
时,它会在user_role表中生成一行。但问题是,当我想访问它时:$user->roles;
,它什么都不返回。它与$role->users;
一起工作,但不能以其他方式工作。我做错了什么?
已解决:Laravel 5.2.29
确保表名为role_user
$user = User::find(1);
$role = Role::find(2);
// In this example I am passing in a Role object but $role->id also works
$user->roles()->attach($role);
希望这对你有用。
像一样附加后,必须重新加载关系
$user->roles()->attach($role);
$user->load('roles');