【问题标题】:select most selled products in range with one query?一次查询选择范围内最畅销的产品?
【发布时间】:2021-11-18 18:26:01
【问题描述】:

是否可以一次查询选择范围内最畅销的产品? 这里的表格:

orders 包含列的表(id、created_at、paid)

order_products(order_id,product_id)

产品(ID、标题)

我试过了,但是没用

\App\Models\Order::with('order_products')->where('paid',1)
        ->whereBetween('created_at',[$request->to,$request->from])
        ->orderBy(\DB::raw('count(order_products.product_id)'))->get());

【问题讨论】:

    标签: laravel


    【解决方案1】:

    假设每个 order_products 代表销售一个产品项目,您可以使用左连接和传统 group by 来做到这一点:

      $mostSalledPrducts = Product::query()
            ->leftJoin('order_products','products.id','=','order_products.product_id')
            ->join('orders','orders.id','=','order_products.order_id')
            ->where('orders.paid',1)
            ->selectRaw('products.*, COALESCE(count(order_products.id),0) total')
            ->groupBy('products.id')
            ->orderBy('total','desc')
            ->take(5)
            ->get();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-19
      • 2014-06-26
      • 1970-01-01
      • 2017-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-03
      相关资源
      最近更新 更多