简体   繁体   中英

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM