Search code examples
laraveleloquentrelationshiphas-many-throughpolymorphic-associations

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?


Solution

  • 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.