簡體   English   中英

Laravel 5 在兩列上有許多關系

[英]Laravel 5 hasMany relationship on two columns

是否可以在兩列上建立 hasMany 關系?

我的表有兩列, user_idrelated_user_id

我希望我的關系匹配任一列。

在我的模型中,我有

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

運行查詢: select * from user_relations where user_relations.user_id in ('17', '18')

我需要運行的查詢是:

select * from user_relations where user_relations.user_id = 17 OR user_relations.related_user_id = 17 

編輯:

我正在使用預先加載,我認為這會影響它的工作方式。

$cause = Cause::with('donations.user.userRelations')->where('active', '=', 1)->first();

我認為不可能完全按照你的要求去做。

我認為您應該將它們視為單獨的關系,然后在模型上創建一個新方法來檢索兩者的集合。

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

public function relatedUserRelations() {
    return $this->hasMany('App\UserRelation', 'related_user_id');
}

public function allUserRelations() {
    return $this->userRelations->merge($this->relatedUserRelations);
}

通過這種方式,您仍然可以在模型上獲得預先加載和關系緩存的好處。

$cause = Cause::with('donations.user.userRelations', 
        'donations.user.relatedUserRelations')
    ->where('active', 1)->first();

$userRelations = $cause->donations[0]->user->allUserRelations();

Compoships在 Laravel 5 的Eloquent 中添加了對多列關系的支持。

它允許您使用以下語法指定關系:

public function b()
{
    return $this->hasMany('B', ['key1', 'key2'], ['key1', 'key2']);
}

其中兩列必須匹配。

我更喜歡這樣做:

public function userRelations()
{
    return UserRelation::where(function($q) {
        /**
         * @var Builder $q
         */
        $q->where('user_id',$this->id)
            ->orWhere('related_user_id',$this->id);
    });
}

public function getUserRelationsAttribute()
{
    return $this->userRelations()->get();
}

如果有人在這里登陸我一樣,由於谷歌:由於沒有合並()(以上所建議的),也不推()(如建議在這里)允許預先加載(和其他不錯的關系特征),討論仍在進行中,並繼續在最近的線程,請參見此處: Laravel Eloquent Inner Join on Self Referencing Table

我在那里提出了一個解決方案,歡迎任何進一步的想法和貢獻。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM