【发布时间】:2016-04-10 15:37:22
【问题描述】:
我正在尝试建立多对多关系,在此示例中为用户和角色。
在用户模型中我得到了这个:
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,但是你必须在两个表之间创建和使用“多对多关系”表。
-
我正在使用取自 Laravel 文档 laravel.com/docs/5.2/eloquent-relationships#many-to-many 的多对多关系示例
标签: php mysql laravel eloquent pivot-table