How should I define two relationships to the same table? Here’s a simple example:
Person
- id
- name
Deal
- id
- seller_person_id
- buyer_person_id
- date
- amount
On the Person model I can have these relationships:
public function deals_seller()
{
return $this->hasMany(Deal::class, 'seller_person_id');
}
public function deals_buyer()
{
return $this->hasMany(Deal::class, 'buyer_person_id');
}
On the Deal model I’ve tried the inverse:
public function seller()
{
return $this->belongsTo(Person::class, null, 'seller_person_id');
}
public function buyer()
{
return $this->belongsTo(Person::class, null, 'buyer_person_id');
}
Using tinker, I can get the deals where a Person is a buyer or seller like this:
$person = Person::where('id',3)->with('deals_seller')->with('deals_buyer')->get();
But, I can’t get the inverse:
$deals = Deal::where('amount', > , 100)->with('buyer')->with('seller')->get();
It doesn’t return the buyer or seller with the deal.
How should I set up the relationships so I can retrieve the buyer and seller for an individual deal or a list of deals?
2
Answers
On the Deal model
You set the
$foreign_key
parameter to null .Read this
To retrieve the buyer and seller for an individual deal or a list of deals, you can define two additional relationships on the
Deal
model, each using thebelongsTo
method to relate to thePerson
model:With these additional relationships, you can retrieve a list of deals with their respective buyer and seller information like this:
This will eager load the
buyer
andseller
relationships for eachDeal
instance in the resulting collection. You can access the buyer and seller information for each deal like this: