在 with() 或 load() Laravel eloquent 之后使用条件过滤器

问题描述 投票:0回答:1

想象我们有一个关于一对多关系的

Facture
Item
模型

我正在使用

$facture->items()
$facture->load('items')
,效果非常好, 但是当我需要像
items
一样在
where('items.price',30)
上使用条件时,我不知道没有
DB::

就可以做到这一点

实际上我尝试使用

leftJoin()
,因为它在关系的右侧有条件,这个解决方案无法帮助我。

laravel eloquent eloquent-relationship
1个回答
0
投票

这似乎是

whereRelation
方法的一个很好的用例,

您可以在查询生成器中执行类似的操作:

->whereRelation('items', 'price', '=', 30)

这将有效地仅返回包含价格为 30 的商品的 Factures。

参考:https://laravel.com/api/10.x/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.html#method_whereRelation

© www.soinside.com 2019 - 2024. All rights reserved.