【问题标题】:Laravel 5 hasMany relationship on two columnsLaravel 5在两列上有很多关系
【发布时间】:2015-06-27 09:54:49
【问题描述】:

是否可以在两列上建立 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();

【问题讨论】:

  • 也许最好只通过这两列过滤UserRelation 模型?

标签: php laravel eloquent laravel-5


【解决方案1】:

我更喜欢这样做:

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

【讨论】:

    【解决方案2】:

    如果有人因为谷歌而像我一样登陆这里: 由于 merge()(如上所述)和 push()(如 here 建议)都不允许预先加载(和其他良好的关系功能),因此讨论仍在进行中,并在更新的线程中继续,请参见此处:@ 987654322@

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

    【讨论】:

    • 请不要只写链接答案。
    【解决方案3】:

    Compoships 在 Laravel 5 的 Eloquent 中增加了对多列关系的支持。

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

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

    两列必须匹配。

    【讨论】:

    • Compoships 是否支持所有列必须匹配的关系或主题所有者要求的关系,即两列中只有一个匹配?从它的描述中看不太清楚。
    • @Namoshek 用户问“是否可以在两列上建立 hasMany 关系?” - 不。使用默认的 Laravel 设置。是的,通过使用 Compoships。要回答您的问题,所有列都必须匹配。
    • @topclaudy 在这种情况下,您的回答并不能真正解决他的问题。作者想要他的relation to match either of the columns,而不是两者。不过,它仍然对其他用户有帮助。也许您应该在答案中明确说明它必须匹配所有列才能工作。
    • @Namoshek 已修复!
    【解决方案4】:

    我认为不可能完全按照您的要求进行。

    我认为您应该将它们视为单独的关系,然后在模型上创建一个新方法来检索两者的集合。

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

    【讨论】:

    • 为什么我会得到这个?调用未定义的方法 Illuminate\\Database\\Query\\Builder::merge()
    • 删除 userRelations @ciccioassenza 后面的括号 :)
    • 嗯,你注意到我在 3 年前问过这个问题 @developerbmw :)
    • 是的,我确实注意到了,但是我忍不住指出了这一点:) @ciccioassenza
    猜你喜欢
    • 1970-01-01
    • 2014-07-10
    • 2015-08-05
    • 2016-10-12
    • 1970-01-01
    • 1970-01-01
    • 2018-07-03
    • 2017-09-03
    • 2019-06-27
    相关资源
    最近更新 更多