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

Set relations on two fields related to the same table

我有一个 users table 有很多用户,例如:

id | name
1  | mike
2  | nina
3  | john 

我还有一个 posts table 和一个 user_id 代表 post 的原始创建者和一个 locked_user_id 如果post 被编辑锁定了。

任何用户都可以锁定或打开 post,但如果 post 被锁定,则只有该用户可以编辑它。这是我的关系:

用户模型:

public function posts(){
    return $this->hasMany('App\Post');
}

Post 型号:

public function user(){
    return $this->belongsTo('App\User');
}

而且我可以通过

轻松检索作者
$posts->user->name

我希望能够同时获得原作者用户和编辑器。例如, post table:

的样本
| id | user_id |    post    | locked_user_id |
| 1  |    1    |  blah blah |       2        |

在这种情况下 $posts->user->name returns mike 但我希望能够获得用户 nina当前正在锁定 post.

我怎样才能做到这一点?

假设 locked_user_id 可以为 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);
}