【问题标题】:Laravel hasMany relation with custom queryLaravel hasMany 与自定义查询的关系
【发布时间】:2018-06-12 11:02:19
【问题描述】:

我有一张Product Orders 的桌子。订单属于Customer(买家),其id 在订单记录中。我可以通过默认hasMany 关系获取客户订单

// Customer model
public function orders() {
  return $this->hasMany(Order::class);
}

另一方面,由于每个Product都属于一个Customer(与订单中id不同的那个)Customer(卖家),我想要另一个Customer可以看到列表Orders 里面有他的Product

当他是卖方或买方时,我想获取客户Orders 的列表。我想创建自定义关系或修改关系以实现结果。

是否可以通过 Laravel 的关系实现这一点?

客户表:

---------------------------
| customer_id |   name    | 
---------------------------
| 1           | seller    |
| 2           | buyer     |

产品表:

---------------------------------------
| product_id  |   name    | seller_id |
---------------------------------------
| 101         | iPhone 6s |   1       |

订单表

----------------------------------------
| order_id  | customer_id | product_id |
----------------------------------------
| 500       | 2           |   101      |

当使用简单的hasMany 关系时,买家会在他的订单列表中看到订单 500。

$buyer->orders();

我想创建一个关系,当我从卖方调用它时,他可以在他的订单列表中看到订单 500。

$seller->orders();

【问题讨论】:

    标签: laravel eloquent relationship


    【解决方案1】:

    我假设你已经定义了所有的关系。使用where() 按买家过滤,使用orWhereHas() 按卖家过滤:

    Order::where('customer_id', auth()->id())
        orWhereHas('product.seller', function($q) {
            $q->where('id', auth()->id());
        })
        ->get();
    

    如果查询中有其他 where 子句,请将 where()orWhereHas()where() 闭包包装起来。

    【讨论】:

    • 我知道如何使用查询生成器检索数据,我希望它是一个雄辩的Relation,以便我可以在其他模型中使用它
    • 我喜欢在我的模型中创建自定义关系,但我不知道如何实现它
    • @Hadu 您可以将此代码用作本地范围,但对于这种情况,您不能定义类似hasMnyThrough 或类似的关系。
    • 有没有办法在 laravel 中定义自定义关系
    • 将其用作示波器是个好主意!为此 +1
    猜你喜欢
    • 2020-11-15
    • 1970-01-01
    • 2019-06-02
    • 2015-12-22
    • 1970-01-01
    • 1970-01-01
    • 2021-10-07
    • 2021-09-24
    • 1970-01-01
    相关资源
    最近更新 更多