Zla*_*umn 3 relationship has-many-through polymorphic-associations laravel eloquent
我有一个包含事务的表,其中每个事务都Transaction属于 aDriver或 a Customer- 所以我在它们之间设置了多态关系。
对于交易我已经设置:
public function owner() {
return $this->morphTo();
}
Run Code Online (Sandbox Code Playgroud)
对于司机和客户:
public function transactions() {
return $this->morphMany(Transaction::class, 'owner');
}
Run Code Online (Sandbox Code Playgroud)
但每个驱动程序也属于一个Company. 我正在尝试获取属于Company直通hasManyThrough关系的所有交易:
public function transactions() {
return $this->hasManyThrough(Transaction::class, Driver::class);
}
Run Code Online (Sandbox Code Playgroud)
但它似乎不适用于多态关系,因为它会抛出错误,因为它试图driver_id在transactions表中查找字段。
通过驱动程序获取属于公司的所有交易的方法是什么?
指定自定义外键并为owner_type列添加约束:
public function transactions() {
return $this->hasManyThrough(Transaction::class, Driver::class, null, 'owner_id')
->where('owner_type', Driver::class);
}
Run Code Online (Sandbox Code Playgroud)
如果没有约束,您将获得具有相同id.