我需要建立一个同时匹配两个字段的
hasOne
关系。
这是我的
users
表:
身份证 | 用户 | 浓缩 | 名字 |
---|---|---|---|
1 | JDoe | ABC | 约翰·多伊 |
2 | JDoe | ZXC | 约翰·多伊 |
这是我的
membership
桌子:
身份证 | 用户 | 浓缩 | 角色 |
---|---|---|---|
1 | JDoe | ZXC | 管理员 |
为了使用需要
membership
模型中关系的另一个组件,我需要同时使用两个标准:user
和 conc
。预期结果是:
$memb = Membership::find(1);
$memb->user; // This should return the user with ID 2, since it has the same 'user' and 'conc'
我尝试过使用
->ofMany
,但似乎我需要一个 join
而不是 where
,而且我无法让它工作。
编辑:
users
表中永远不会有两条具有相同 user
和 conc
的记录,因此存在 hasOne
而非 hasMany
关系。
您可以使用关系定义中的
hasOne
子句来定义具有多个条件的 where
关系。
public function user()
{
return $this->hasOne(User::class, 'user', 'user')
->where('conc', $this->conc);
}
然后,您可以从
User
模型实例访问相关的 Membership
模型,如下所示。
$memb = Membership::find(1);
$user = $memb->user; // This will return the User model with the same 'user' and 'conc' as the Membership model