Laravel 将查询生成器转换为雄辩的
我有这些桌子:Laravel 将查询生成器转换为雄辩的,laravel,eloquent,Laravel,Eloquent,我有这些桌子: 产品:id、名称 订单:身份证号码 订单项目:订单id、产品id 所以我想订购最好的产品。下面是我的代码 $sales = DB::table('products') ->leftJoin('order_items','products.id','=','order_items.product_id') ->leftJoin('orders','orders.id','=','order_items.order_id
- 产品:id、名称
- 订单:身份证号码
- 订单项目:订单id、产品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();
请帮我把上面的问题转换成雄辩的。这项工作很有效,但我也希望获得变形的产品图像。假设您在
产品
模型中创建了正确的关系,则会出现如下情况:
Product::with('order_items', 'orders')
->selectRaw('COALESCE(sum(orders.item_count),0) as total')
->orderByDesc('total')
->limit(6)
->get();
$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();
假设您在
产品
模型中创建了正确的关系,则如下所示:
Product::with('order_items', 'orders')
->selectRaw('COALESCE(sum(orders.item_count),0) as total')
->orderByDesc('total')
->limit(6)
->get();
$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();
Eloquent还支持
leftJoin
,因此您可以执行以下操作:
Product::with('order_items', 'orders')
->selectRaw('COALESCE(sum(orders.item_count),0) as total')
->orderByDesc('total')
->limit(6)
->get();
$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();
但是,如果您想使用Earge load,请先共享您的模型和这些关系,Eloquent还支持
leftJoin
,因此您可以这样做:
Product::with('order_items', 'orders')
->selectRaw('COALESCE(sum(orders.item_count),0) as total')
->orderByDesc('total')
->limit(6)
->get();
$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();
但是,如果您想使用Earge load,请先共享您的模型和这些关系,在文章中共享这些表的模型。另外,也要解释这个查询到底在做什么,并提供一些使用数据的示例。您是否为这些表创建了模型,如果是,请在此处共享。在文章中共享这些表的模型。另外,也要解释这个查询到底在做什么,并提供一些使用数据的示例。您是否为这些表创建了模型,如果是,请在此处共享。