3

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?

Zlautumn
  • 89
  • 1
  • 11

1 Answers1

10

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.

Jonas Staudenmeir
  • 24,815
  • 6
  • 63
  • 109
  • That works, thanks! And also answers my question about getting transactions of other owners with the same `id`. Only one question left: what does `null` stand for? I seem to have tried quite the same, but like ` return $this->hasManyThrough(Transaction::class, Driver::class, null, 'owner_id')`. – Zlautumn Oct 31 '18 at 06:08
  • The third argument is the foreign key in the `drivers` table. When you pass `null`, Laravel uses the default `company_id`. You can also pass the value explicitly. – Jonas Staudenmeir Oct 31 '18 at 12:43