Reputation: 352
Seeting up a laravel 5 project, in which I have an unusual relationship to create.
the model Foo connects to exactly two instances of the model Bar (under different keys), but each Bar can only connect to a single Foo, regardless of which of the two fields it is occupying. i.e.
Foo
id
barA()
barB()
Bar
id
foo()
Not sure how to properly map this in terms of relationships. I've tried
Foo{
public function barA(){
return $this->belongsTo('\App\Bar','bar_a_id');
}
public function barB(){
return $this->belongsTo('\App\Bar','bar_b_id');
}
}
Which works reasonably well, but there I can't figure out how to create the flipside of the relationship.
I know I could use a 1:m relationship, but then it becomes ambiguous which entity is 'a' and which is 'b'.
anyone have any advice?
Upvotes: 1
Views: 80
Reputation: 9883
The way I would go about this would be to use a One-To-Many relation and use model observers to enforce the limitations.
As for identifying a and b is there something else in the object you can identify these by? You could always store a column on the model itself and use a scope to pull the correct one out. So you'd end up with something like $foo->bar()->a()->first()
and $foo->bar()->b()->first()
I would avoid using the 2 column approach like in your question. Done that on an older project, its horrid.
Upvotes: 1