繁体   English   中英

在与同一表相关的两个字段上设置关系

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM