首页 > 解决方案 > 将查询生成器转换为 Eloquent

问题描述

我有这些表:

所以我想得到最好的订单产品。我在下面制作了这段代码。

$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();

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

标签: laraveleloquent

解决方案


Eloquent 也支持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();

但是如果你的意思是你想使用 eager load,请先分享你的模型和这些关系,


推荐阅读