简体   繁体   中英

laravel collection nested "where"

Assume the following collection:

 [
   order
    -id
    -receiverAddress
    -...
    relations
        transactions
            -id
            -transaction_id_external
            - ...
 ]

I tried to use the following filter on the collection:

    $isNotEmpty = $orders->filter(function ($order) use ($receivedPaymentDetails) {
        return $order->transactions
            ->where('transaction_id_external', $receivedPaymentDetails->txid)
            ->where('order.receiverAddress', $receivedPaymentDetails->address)
            ->isNotEmpty();
    })->isNotEmpty();

It seems like this doesn't work, any idea how I can filter on the parent collection item order.receiverAddress?

Since you want to filter based on the transactions relations, you must perform some form of join query with your transactions table

Easiest way for you would be to place your queries in a whereHas callback

$isNotEmpty = $orders->filter(function ($order) use ($receivedPaymentDetails) {
            return $order->whereHas('transactions', function ($query) use ($receivedPaymentDetails) {
                $query->where('transactions.transaction_id_external', $receivedPaymentDetails->txid);
                $query->where('order.receiverAddress', $receivedPaymentDetails->address);
            })
                ->isNotEmpty();
        })->isNotEmpty();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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