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();
请帮我将上面的查询转换为雄辩的。这项工作,但我也想获得产品变形图像。
解决方案
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,请先分享你的模型和这些关系,
推荐阅读
- user-interface - 尚未上线客户端的经典界面与统一界面
- html - 使用谷歌应用脚本格式化的高级发送邮件 - 邮件中的灵活内容
- yii2 - 如何从导出配置中删除列
- azure-cosmosdb - Cosmos DB中collection的id是如何选择的?
- c# - 无法使用具有 MVVM 模式的每个 BackgroundWorker 填充模型数据
- vuejs2 - Vue计算属性:尽管已定义,但帮助函数返回未定义
- angular - 是否可以对绑定到角度属性的值进行数学运算
- html - 在 CSS 中定义替代图像路径
- visual-studio - 在每次构建之前运行自定义工具,即使它是最新的
- java - 安卓 Gson 棉花糖