简体   繁体   English

Laravel - 关闭关系的过滤器集合

[英]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.payementMethodsempty

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM