【问题标题】:Laravel hasManyThrough a polymorphic relationLaravel hasMany通过多态关系
【发布时间】:2019-04-04 05:10:34
【问题描述】:

我有一个事务表,其中每个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 字段。

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

【问题讨论】:

    标签: laravel eloquent relationship has-many-through polymorphic-associations


    【解决方案1】:

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

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

    如果没有约束,您将获得具有相同id 的不同所有者的交易。

    【讨论】:

    • 行得通,谢谢!并且还回答了我关于使用相同的id 与其他所有者进行交易的问题。只剩下一个问题:null 代表什么?我似乎尝试过同样的方法,但是就像`return $this->hasManyThrough(Transaction::class, Driver::class, null, 'owner_id')`。
    • 第三个参数是drivers表中的外键。当你传递 null 时,Laravel 使用默认的 company_id。您也可以显式传递值。
    猜你喜欢
    • 1970-01-01
    • 2014-09-30
    • 1970-01-01
    • 2014-12-13
    • 2020-08-04
    • 2020-04-16
    • 2019-10-01
    • 2017-09-03
    • 1970-01-01
    相关资源
    最近更新 更多