[英]Laravel - Filter collection with closure on relationship
Wondering if there is a way to use closure on a relationship in order to filter the whole line if there isn't a value which corresponds?想知道是否有办法在关系上使用闭包来过滤整行,如果没有对应的值?
Example code:示例代码:
foreach ($paiementMethods as $value) {
$giftCards = GiftCard::with(['userEntered', 'userEmployee', 'client', 'payement', 'payement.payementMethods' => function($query) use ($value)
{
$query->where('id', $value);
}])
->where('date','>=', $dateStart)
->where('date','<=', $dateEnd)
->orderBy('updated_at', 'desc')->get();
$giftCardsCollection = $giftCardsCollection->merge($giftCards);
}
}
In this example, if $query->where
doesn't find a row for the payement.payementMethods
which matches the $value
, I want the giftCard
to return null.在此示例中,如果
$query->where
没有找到与$value
匹配的payement.payementMethods
行,我希望giftCard
返回 null。 The result I get is the giftCard
with only the relation on payement.payementMethods
being empty
.结果我得到的是
giftCard
只对关系payement.payementMethods
是empty
。
My other solution would be to query the giftCard and after that checking the $value
to see if I have to include the giftCard in the collection or not.我的另一个解决方案是查询礼品卡,然后检查
$value
以查看是否必须在集合中包含礼品卡。
Best regards此致
I think using whereHas
, it can be solved我认为使用
whereHas
,可以解决
$giftCards = GiftCard::with(['userEntered', 'userEmployee', 'client', 'payement', 'payement.payementMethods'])
->whereHas( 'payement.payementMethods', function($query) use ($paiementMethods) {
$query->whereIn('id', $paiementMethods);
})
->where('date','>=', $dateStart)
->where('date','<=', $dateEnd)
->orderBy('updated_at', 'desc')
->get();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.