Eloquent multiple row relationship with Laravel

105 views Asked by At

I can't rack my head how to create a relationship that involves having two records of the same model in another table. I am trying to keep record of company acquisitions (M&A) in a certain geography and in order to do that I have to keep record of the acquirer and the acquired both of which I may or may not have in our company table.

Here's a simple example:

ABC acquires XYZ

Acquisition table

acquirer | acquired | type          | acquirer_id | acquiree_id
ABC        XYZ        acquisition     34            58

Company table

id | name | slug 
34 | ABC  | abc
58 | XYZ  | xyz

I'm not entirely sure if this is a good approach but I would like to be able to display the acquisition on both profiles.

E.g: On ABC's profile, we show that ABC acquired XYZ and on XYZ's profile, we show that XYZ has been acquired by ABC. I'll need to get the company's slug (if company exists) so that I am able to link to it while showing the acquisition.

1

There are 1 answers

0
Warren Clarin On

I am not sure if this answers your problem. You can declare two relationship in your Acquisition Model.

public function acquirerCompany() {
    return $this->belongsTo(Company::class, 'acquirer_id');
}

public function acquireeCompany() {
    return $this->belongsTo(Company::class, 'acquiree_id');
}

Now if you want to get the company slug:

// acquierer
$acquisition->acquirerCompany->slug;

// acquieree
$acquisition->acquireeCompany->slug;