问题
I have two models
model_1
model_2
model_1
has many 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)
How can I do this in hasMany
association
回答1:
I got it to work by adding an additional parameter to join on in the model:
public function my_joined_columns($mySecondJoinColumnValue)
{
return $this->hasMany('NamespaceToOtherModel', 'myIdColumn')
->where('my_second_join_column', $mySecondJoinColumnValue);
}
And then I make sure I pass in the parameter:
MyModel1::find(1)->my_joined_columns(2)->get()
回答2:
I faced this situation while dealing with a pre existing schema. I came up with this solution
After installing Compoships and configuring it in your models model_1 and model_2, you can define your relationships matching multiple columns.
In model_1:
public function model_2()
{
return $this->hasMany(model_2::class, ['f1', 'f2'], ['f1', 'f2']);
}
In model_2:
public function model_1()
{
return $this->belongsTo(model_1::class, ['f1', 'f2'], ['f1', 'f2']);
}
Compoships supports eager loading.
回答3:
Official Laravel Docummentation says: http://laravel.com/docs/5.1/eloquent-relationships#one-to-many
来源:https://stackoverflow.com/questions/32471084/laravel-hasmany-association-with-multiple-columns