laravel 根据关系筛选集合

laravel filter collection based on relation

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

订单

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 的过滤不是这样工作的? 它 returns 是一个空元素,即使交易 ID 在集合中也是如此。

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

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

您应该试试 whereHas。

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

如果没有找到,那么你应该仔细检查数据库中是否没有与 $receivingPayment id 不匹配。

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