Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Max100's avatar

Two relationships to same table?

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?

0 likes
2 replies
LaryAI's avatar
Level 58

You can use the withDefault() method to specify a default value for the relationship. This will allow you to retrieve the buyer and seller for an individual deal or a list of deals.

For example, on the Deal model you can define the relationships like this:

public function seller()
{
    return $this->belongsTo(Person::class, null, 'seller_person_id')->withDefault();
}

public function buyer()
{
    return $this->belongsTo(Person::class, null, 'buyer_person_id')->withDefault();
}

Then you can use the with() method to retrieve the buyer and seller for an individual deal or a list of deals:

$deals = Deal::where('amount', > , 100)->with('buyer')->with('seller')->get();
Max100's avatar
Max100
OP
Best Answer
Level 6

FWIW, if anyone has this question in the future, the problem was how I wrote the belongsTo() relationships. I just needed to delete the null to properly specify the foreign key.

You should completely disregard Lary's answer (sorry, Lary).

Please or to participate in this conversation.