我很难在 Laravel 5 中的三个表/模型之间创建三向多对多关系。到目前为止,从网上查找还没有给我任何可行的解决方案。
我有三个模型:用户、角色、论文。
我想实现的是将三者相互联系起来。例如,一个用户可以与许多论文相关联,这个用户可以在一个特定的<强>论文强>。
因此,一个用户可以在一个特定的论文上拥有多个角色(例如讲师和审稿人),并且同一个用户也可以关联与另一个thesis 并在其中扮演另一个角色(例如仅限讲师)。
到目前为止,我已经尝试了一种方法,即创建另一个模型来处理数据透视表。所以我创建了一个模型 Relation。
我现在的表:
用户
id
name
论文
id
topic
角色
id
name
关系
id
role_id (references id on roles)
thesis_id (references id on theses)
user_id (references id on users)
还有我现在拥有的代码
User.php
class User extends Authenticatable
{
public function relations(){
return $this->hasMany('App\Relation', 'relations');
}
}
Thesis.php
class Thesis extends Model
{
public function relations(){
return $this->hasMany('App\Relation', 'relations');
}
}
Role.php
class Role extends Model
{
public function relations(){
return $this->hasMany('App\Relation', 'relations');
}
}
Relation.php
class Relation extends Model
{
public function user(){
return $this->belongsToMany('App\User');
}
public function thesis(){
return $this->belongsToMany('App\Thesis');
}
public function role(){
return $this->belongsToMany('App\Role');
}
}
现在我在插入数据透视表时使用 $relation = new Relation; 方法。
我不知道如何从数据透视表中获取数据。例如获取用户的论文以及用户在该特定论文<上的角色/强>。
我尝试过类似$user->thesis() 或$user->role() 或$user->thesis()->role() 但它们都不起作用。我只收到未定义的方法错误。
如果我能得到一些帮助或至少某种方向,我将非常感激,即使我在这里展示的内容有些正确。
谢谢。
最佳答案
您对 Many to Many relationship 感兴趣它通过中间表存储关系。中间表可以存储附加属性,因此,您可以创建一个带有附加 role_id
属性的 thesis_users
中间表。该文档在“检索中间表列”标题下介绍了此用例。您不需要额外的模型来表示这些关系。
如果您需要确定哪个Thesis
用户具有特定的角色
,您可以查询中间表(也称为数据透视表
) > 关于,例如:
return $this->belongsToMany('App\Thesis')->wherePivot('role_id', 1);
您的用户模型关系看起来像这样:
public function theses()
{
return $this->belongsToMany('App\Thesis');
}
您的 Thesis 模型关系看起来像这样:
public function users()
{
return $this->belongsToMany('App\User');
}
然后你可以对你的 Thesis 模型做额外的关系约束,像这样:
public function authors()
{
return $this->belongsToMany('App\User')->wherePivot('role_id', 1);
}
public function reviewers()
{
return $this->belongsToMany('App\User')->wherePivot('role_id', 2);
}
public function instructors()
{
return $this->belongsToMany('App\User')->wherePivot('role_id', 3);
}
在你的用户模型上是这样的:
public function authored()
{
return $this->belongsToMany('App\Thesis')->wherePivot('role_id', 1);
}
public function reviewer()
{
return $this->belongsToMany('App\Thesis')->wherePivot('role_id', 2);
}
等等
Thesis::find(1)->reviewers(); // returns every App\User with the role_id 2 on App\Thesis with ID 1
Thesis::find(1)->instructors(); // returns every App\User with the role_id 3 on App\Thesis with ID 1
User::find(1)->theses(); // returns each App\Thesis that the user has any role on
User::find(1)->authored(); // returns each App\Thesis that the user has the author role on
关于php - 如何在 Laravel 中定义三向多对多关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48481244/