skip to Main Content

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


  1. On the Deal model

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

    You set the $foreign_key parameter to null .

    Read this

    Login or Signup to reply.
  2. 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 the belongsTo method to relate to the Person model:

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

    With these additional relationships, you can retrieve a list of deals with their respective buyer and seller information like this:

    $deals = Deal::where('amount', '>', 100)->with('buyer', 'seller')->get();
    

    This will eager load the buyer and seller relationships for each Deal instance in the resulting collection. You can access the buyer and seller information for each deal like this:

    foreach ($deals as $deal) {
        echo "Deal ID: " . $deal->id . "n";
        echo "Seller: " . $deal->seller->name . "n";
        echo "Buyer: " . $deal->buyer->name . "n";
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search