基于关系的laravel过滤器集合

时间:2021-06-14 12:47:52

标签: php laravel collections

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

订购

public function transactions(){

    return $this->hasMany('App\Transaction');
}

已加载集合 ($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 在集合中,它也会返回一个空元素。

3 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

你应该试试 whereHas。

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

如果没有发现任何东西,那么您应该仔细检查数据库中是否与 $receivingPayment id 不匹配。

答案 2 :(得分:0)

如果您不能或不想使用上述答案并继续使用您拥有的集合,请使用 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();
})