【问题标题】:Laravel: Best way to compare two collections: whereIn?Laravel:比较两个集合的最佳方法:whereIn?
【发布时间】:2018-03-30 15:09:14
【问题描述】:

我有一个包含类别的表,一个包含产品的表和另一个跟踪用户拥有的产品的表 products_user。

在页面上显示产品时,如果用户拥有该产品,则应将按钮从“购买”更改为“已购买”。

我通过 $categories->products 显示产品。找出用户已经拥有哪些产品的最有效方法是什么?

我不想将用户拥有的产品的整个集合加载到内存中,因为它们可能有数千个。我也不想为每个检查创建一个 Mysql 查询。

where 子句有一个选项。但即便如此,我还是有一种更聪明的方法来创建这个子句,而不需要遍历每个产品来构建一个数组。

有人可以帮我想出一个好的逻辑吗?谢谢

【问题讨论】:

  • 一般来说,在SQL方面,您可以将用户的产品左连接到您选择的类别中的产品的查询中。对于用户不拥有的类别中的产品,用户产品列将为空。您不会以这种方式加载整个用户产品集合;只有类别中的那些。

标签: php laravel eloquent


【解决方案1】:

您可以使用Constraining Eager Loads 将更多信息附加到您的产品中。在这种情况下,user_id 是NULLuser_id,表示用户是否购买了产品。

$categories = Category::with(['products' => function ($q) {
    $q->select(['products.*', 'user_id'])
        ->leftJoin('products_user', 'user_products.product_id', '=', 'products.id')
        ->where(function ($q) {
            $q->whereNull('user_id')->orWhere('user_id', Auth::user()->id);
        });
}])->get();

foreach ($categories as $category) {
    $products = $category->products;
    foreach ($products as $product) {
        if (empty($product->user_id)) {
            // user not yet bought the product
        }
        else {
            // user already bought the product
        }
     }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-03
    • 1970-01-01
    • 2012-05-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多