Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel hasManyThrough a polymorphic relation

I have a table with transactions where every Transaction belongs to either a Driver, or a Customer - so I set a polymorphic relation between them.

For Transaction I have set:

public function owner() {
    return $this->morphTo();
}

For Driver and Customer:

public function transactions() {
    return $this->morphMany(Transaction::class, 'owner');
}

But each driver also belongs to a Company. And I am trying to get all transactions that belong to a Company through hasManyThrough relation:

public function transactions() {
    return $this->hasManyThrough(Transaction::class, Driver::class);
}

But it seems to not work on a polymorphic relations, as it throws an error because it tries to look for a driver_id field at transactions table.

What is the way to get all the transactions that belong to a Company through its drivers?

like image 501
Zlautumn Avatar asked Oct 18 '25 06:10

Zlautumn


1 Answers

Specify the custom foreign key and add a constraint for the owner_type column:

public function transactions() {
    return $this->hasManyThrough(Transaction::class, Driver::class, null, 'owner_id')
        ->where('owner_type', Driver::class);
}

Without the constraint, you would get transactions of different owners that have the same id.

like image 150
Jonas Staudenmeir Avatar answered Oct 20 '25 06:10

Jonas Staudenmeir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!