Laravel 5 两列有很多关系

Laravel 5 hasMany relationship on two columns

是否可以在两列上建立 hasMany 关系?

我的 table 有两列,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.

中添加了对 multi-columns 关系的支持

它允许您使用以下语法指定关系:

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

两列必须匹配。

如果有人像我一样因为google来到这里: 既不是 merge() (如上建议)也不是 push() (如建议 here) allow eager loading (and other nice relation features), the discussion is still ongoing and was continued in a more recent thread, see here: Laravel Eloquent Inner Join on Self Referencing Table

我提出了一个解决方案there,欢迎任何进一步的想法和贡献。

我更喜欢这样做:

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();
}