[英]Set relations on two fields related to the same table
我有一个包含许多用户的users
表,例如:
id | name
1 | mike
2 | nina
3 | john
我还具有一个posts
表,其中的user_id
代表该posts
的原始创建者,如果该帖子被编辑者锁定,则将填充一次locked_user_id
。
任何用户都可以锁定或打开该帖子,但是如果该帖子被锁定,则只有该用户可以编辑它。 这是我的关系:
用户模型:
public function posts(){
return $this->hasMany('App\Post');
}
帖子模型:
public function user(){
return $this->belongsTo('App\User');
}
我可以通过以下方式轻松检索作者
$posts->user->name
我希望能够同时获得原始创建者用户和编辑者。 例如,post表的示例:
| id | user_id | post | locked_user_id |
| 1 | 1 | blah blah | 2 |
在这种情况下, $posts->user->name
返回mike,但我希望能够获得当前正在锁定该帖子的用户nina 。
我该怎么做?
假设locked_user_id
可以为null,并且如果为null,则返回的用户基于used_id
,您可以将Post
模型上的user()
关系更新为:
public function user()
{
if (!is_null($this->locked_user_id)) {
return $this->belongsTo('App\User', 'locked_user_id', 'id');
}
return $this->belongsTo('App\User');
}
因此,如果存在locked_user_id
,则返回的用户基于此字段,否则返回的用户基于user_id
字段
根据评论,如果要访问这两个用户,则可以在Post
模型上添加另一个关系。 例如
// Assuming `user_id` is not nullable, this will always return the original user
public function creator()
{
return $this->belongsTo('App\User');
}
// Assuming `locked_user_id` is nullable, this will return either `null`, if there is no editor or the user that locked the post
public function editor()
{
return $this->belongsTo('App\User', 'locked_user_id', 'id');
}
在您的代码上,您可以执行以下操作:
if (is_null($this->editor)) {
dd('There is no editor');
} elseif ($this->editor->id === $this->creator->id) {
dd('The original creator has locked the post');
} else {
dd('The post was created by ' . $this->creator->name. ' but now is locked by ' . $this->editor->name);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.