Laravel具有许多与多个列的关联 [英] Laravel hasMany association with multiple columns

查看:40
本文介绍了Laravel具有许多与多个列的关联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个型号

model_1
model_2

model_1 有很多 model_2

现在我要关联model_1 hasmany model_2与多个列匹配.

Now I want to association model_1 hasMany model_2 match with multiple column.

让我在原始查询中举一个例子

Let me give an example in raw query

select ...... from model_1 left join model_2 ON (model_1.f1 = model_2.f1 AND model_1.f2 = model_2.f2)

我该如何在 hasMany 关联

推荐答案

我在处理现有架构时遇到了这种情况.我想出了此解决方案

I faced this situation while dealing with a pre existing schema. I came up with this solution

在安装 Compoships 并在模型 model_1 model_2 ,您可以定义与多个列匹配的关系.

After installing Compoships and configuring it in your models model_1 and model_2, you can define your relationships matching multiple columns.

在model_1中:

public function model_2()
    {
        return $this->hasMany(model_2::class, ['f1', 'f2'], ['f1', 'f2']);
    }

在model_2中:

public function model_1()
    {
        return $this->belongsTo(model_1::class, ['f1', 'f2'], ['f1', 'f2']);
    }

Compoships支持紧急加载.

Compoships supports eager loading.

这篇关于Laravel具有许多与多个列的关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆