基于关系的laravel过滤器集合



假设以下代码表示订单和相关交易:

订单

public function transactions(){
return $this->hasMany('AppTransaction');
}

已加载集合($orders(

order1
id
amount
transactions (relation)
txid
method
amount
order2
id
amount
transactions (relation)
txid
method
amount

以下对已加载集合的筛选无法按预期工作:

$isNotEmpty = $orders->filter(function ($order) use ($receivingPayment) {
return $order->transactions->txid === $receivingPayment->txid && $order->transactions->method === $receivingPayment->method;
})->isNotEmpty();

似乎对关系transactions的过滤不这样工作?即使事务id在集合中,它也会返回一个空元素。

如果您不能或不想使用上面的答案并继续使用您的集合,请使用filterpluck:的组合

$orders->filter(function ($order) use ($receivingPayment) {
return $order->transactions
->pluck('id')
->containsStrict($receivingPayment->txid);
})

要筛选与单个事务匹配的多个条件,请使用多个whereisNotEmpty():的组合

$orders->filter(function ($order) use ($receivingPayment) {
return $order->transactions
->where('txid', $receivingPayment->txid)
->where('method', $receivingPayment->method)
->isNotEmpty();
})

您想要的不是过滤订单,而是过滤交易。你可以这样做:

$orders->transactions()->where('transactions.txid', '=', $receivingPayment->txid)->get();

您应该尝试whereHas。

$orders->whereHas('transactions', function($query) use ($receivingPayment) { $query->where('txid', '=' $receivingPayment->txid})->count();

若并没有找到任何东西,那个么您应该加倍检查数据库中是否存在与$receivingPayment id不匹配的情况。

最新更新