簡體   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