【问题标题】:Laravel hasMany association with multiple columnsLaravel hasMany关联多列
【发布时间】:2015-12-04 22:08:56
【问题描述】:
我有两个模型
model_1
model_2
model_1 有很多model_2
现在我想关联 model_1 hasMany model_2 与多列匹配。
让我举一个原始查询的例子
select ...... from model_1 left join model_2 ON (model_1.f1 = model_2.f1 AND model_1.f2 = model_2.f2)
如何在hasMany 关联中做到这一点
【问题讨论】:
标签:
php
laravel
laravel-4
laravel-5
eloquent
【解决方案1】:
我在处理预先存在的架构时遇到了这种情况。我想出了this solution
安装Compoships 并在您的模型model_1 和model_2 中配置后,您可以定义匹配多个列的关系。
在模型_1 中:
public function model_2()
{
return $this->hasMany(model_2::class, ['f1', 'f2'], ['f1', 'f2']);
}
在模型_2 中:
public function model_1()
{
return $this->belongsTo(model_1::class, ['f1', 'f2'], ['f1', 'f2']);
}
Compoships 支持预加载。
【解决方案2】:
我通过在模型中添加一个附加参数来使其工作:
public function my_joined_columns($mySecondJoinColumnValue)
{
return $this->hasMany('NamespaceToOtherModel', 'myIdColumn')
->where('my_second_join_column', $mySecondJoinColumnValue);
}
然后我确保我传入了参数:
MyModel1::find(1)->my_joined_columns(2)->get()