简体   繁体   English

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

[英]Set relations on two fields related to the same table

I have a users table with many users, for example: 我有一个包含许多用户的users表,例如:

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

I also have a posts table with a user_id that represents the original creator of the post and a locked_user_id that is filled if the post was locked by an editor. 我还具有一个posts表,其中的user_id代表该posts的原始创建者,如果该帖子被编辑者锁定,则将填充一次locked_user_id

Any user can lock or open the post but if the post is locked only that user can edit it. 任何用户都可以锁定或打开该帖子,但是如果该帖子被锁定,则只有该用户可以编辑它。 This are my relations: 这是我的关系:

User model: 用户模型:

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

Post model: 帖子模型:

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

And I can retrieve the author easily by 我可以通过以下方式轻松检索作者

$posts->user->name

I would like to be able to get both the original creator user and the editor. 我希望能够同时获得原始创建者用户和编辑者。 For instance, a sample of the post table: 例如,post表的示例:

| id | user_id |    post    | locked_user_id |
| 1  |    1    |  blah blah |       2        |

In this case $posts->user->name returns mike but I want to be able to get the user nina which is currently locking the post. 在这种情况下, $posts->user->name返回mike,但我希望能够获得当前正在锁定该帖子的用户nina

How can I accomplish this? 我该怎么做?

Assuming locked_user_id can be null, and, if so, the returned user is based on the used_id , you could update the user() relation on the Post model to: 假设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');
}

So, if there's a locked_user_id the returned used is based on this field, otherwise the returned user is based on the user_id field 因此,如果存在locked_user_id ,则返回的用户基于此字段,否则返回的用户基于user_id字段


As per the comment, if you want to access both users, you can add another relation on the Post model. 根据评论,如果要访问这两个用户,则可以在Post模型上添加另一个关系。 For instance 例如

// 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');
}

On your code you can do something like: 在您的代码上,您可以执行以下操作:

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