将查询生成器转换为雄辩

时间:2020-07-26 11:33:21

标签: laravel eloquent

我有这些表:

  • 产品:ID,名称
  • 订单:id,数字
  • order_items:order_id,product_id

所以我想获得最好的订购产品。我在下面编写这段代码。

$sales = DB::table('products')
            ->leftJoin('order_items','products.id','=','order_items.product_id')
            ->leftJoin('orders','orders.id','=','order_items.order_id')
            ->selectRaw('products.*, COALESCE(sum(orders.item_count),0) total')
            ->groupBy('products.id')
            ->orderBy('total','desc')
            ->take(6)
            ->get();

请帮助我将上面的查询转换为雄辩的。这项工作,但我也想让产品变形图像。

2 个答案:

答案 0 :(得分:1)

假设您在Product模型中创建了正确的关系,则看起来像这样:

Product::with('order_items', 'orders')
    ->selectRaw('COALESCE(sum(orders.item_count),0) as total')
    ->orderByDesc('total')
    ->limit(6)
    ->get();

答案 1 :(得分:1)

口才还支持leftJoin,因此您可以执行以下操作:

$sales = Product::query()
            ->leftJoin('order_items','products.id','=','order_items.product_id')
            ->leftJoin('orders','orders.id','=','order_items.order_id')
            ->selectRaw('products.*, COALESCE(sum(orders.item_count),0) total')
            ->groupBy('products.id')
            ->orderBy('total','desc')
            ->take(6)
            ->get();

但是,如果您要使用急切负载,请先共享您的模型和这些关系,