繁体   English   中英

Laravel有很多通过多态关系

[英]Laravel hasManyThrough a polymorphic relation

我有一个包含事务的表,其中每个Transaction属于DriverCustomer ,所以我在它们之间设置了多态关系。

对于交易,我已设置:

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

对于驾驶员和客户:

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

但是每个驱动程序也属于一个Company 我试图通过hasManyThrough关系获取属于Company所有交易:

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

但是它似乎不适用于多态关系,因为它会尝试在transactions表中查找driver_id字段,从而引发错误。

通过其驱动程序获取属于公司的所有交易的方式是什么?

指定自定义外键,并为owner_type列添加约束:

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

没有约束,您将获得具有相同id的不同所有者的事务。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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