【问题标题】:laravel filter collection based on relationlaravel 基于关系的过滤器集合
【发布时间】:2021-08-30 08:59:54
【问题描述】:

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

订购

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

【问题讨论】:

    标签: php laravel collections


    【解决方案1】:

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

    【讨论】:

    • 不能在where 集合方法中使用关系?
    • 在你的情况下,transactions 是一个包含多个事务而不是单个事务的数组(所以最合乎逻辑的做法是使用 transactions.*.txid 作为参数,但不幸的是 Laravel 不支持这种语法)。但这仍然会返回一个集合,您可以使用它来检查 isNotEmpty() 是否包含任何值。
    • transactions 本身就是一个数组/集合,你能举例说明如何检查吗?
    • 我的答案就是例子。您可以在 where 中使用关系和访问关系的属性,但前提是它是单个关系(如 hasOnebelongsTo),但不能在集合内(如 hasMany)。跨度>
    • 谢谢。有没有一种简单的方法可以在filter() 方法中包含method 以进行额外检查?所以我也可以附上付款方式的支票?
    【解决方案2】:

    你应该试试 whereHas。

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

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

    【讨论】:

    • 我想过滤集合,而不是查询库。数据已从数据库中获取。
    【解决方案3】:

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

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

    【讨论】:

    • 我想过滤集合,而不是查询库。数据已从数据库中获取。
    猜你喜欢
    • 2021-03-09
    • 2014-01-22
    • 1970-01-01
    • 2020-10-30
    • 2013-09-14
    • 1970-01-01
    • 1970-01-01
    • 2015-03-06
    • 1970-01-01
    相关资源
    最近更新 更多