
本文旨在提供一种使用 Laravel Eloquent ORM 通过关联模型获取并分组数据的有效方法。我们将以餐厅、菜品和订单之间的关系为例,展示如何使用 with() 和 whereHas() 方法,避免使用循环,从而编写更简洁、更高效的代码。通过本文,你将学会如何根据订单 ID 对结果进行分组,并获得包含菜品及其数量的结构化数据。
利用 Eloquent 关联关系获取数据
在 Laravel 应用中,经常需要通过关联关系获取数据。例如,在一个餐厅应用中,一个餐厅可以有多个菜品,一个菜品可以属于多个订单,一个订单可以包含多个菜品。
假设我们有三个模型:Restaurant(餐厅)、Dish(菜品)和 Order(订单)。它们之间的关系如下:
Restaurant has many DishDish belongs to many RestaurantDish belongs to many Order with pivot quantityOrder belongs to many Dish
以下是模型的定义:
// Restaurant 模型class Restaurant extends Authenticatable{ public function dishes() { return $this->belongsToMany('AppModelsDish'); }}// Dish 模型class Dish extends Model{ public function orders() { return $this->belongsToMany('AppModelsOrder')->withPivot('quantity'); } public function restaurant() { return $this->belongsToMany('AppModelsRestaurant'); }}// Order 模型class Order extends Model{ public function dishes() { return $this->belongsToMany('AppModelsDish')->withPivot('quantity'); }}
使用 with() 和 whereHas() 进行高效查询
为了获取特定餐厅的所有订单,并按照订单 ID 分组,我们可以使用 with() 和 whereHas() 方法,避免使用循环,提高查询效率。
以下是查询的代码示例:
use AppModelsOrder;use IlluminateDatabaseEloquentBuilder;public function index($restaurant_id){ $orders = Order::with('dishes') ->whereHas('dishes', function (Builder $dishes) use ($restaurant_id) { $dishes->where('restaurant_id', $restaurant_id); })->get(); return response()->json($orders);}
代码解释:
Order::with(‘dishes’):使用 with() 方法预加载订单关联的菜品,减少 N+1 查询问题。->whereHas(‘dishes’, …):使用 whereHas() 方法筛选包含指定餐厅菜品的订单。function (Builder $dishes) use ($restaurant_id) { … }:在 whereHas() 方法中使用闭包,以便访问外部变量 $restaurant_id。$dishes->where(‘restaurant_id’, $restaurant_id):在闭包中,筛选菜品表中 restaurant_id 等于指定餐厅 ID 的菜品。->get():获取符合条件的订单集合。
返回结果示例:
上述代码将返回一个 JSON 格式的订单数组,每个订单对象包含其关联的菜品信息,例如:
[ { "id": 28, "status": 1, "address": "Fish Street", "user_name": "Artyom", "user_surname": "Pyotrovich", "phone": "351 351 643 52", "email": "email@protected", "total": 35.8, "created_at": "2021-11-17T10:44:58.000000Z", "updated_at": "2021-11-17T10:44:58.000000Z", "dishes": [ { "id": 22, "name": "Delicious Pizza", "description": "...", "created_at": "...", "updated_at": "...", "pivot": { "order_id": 28, "dish_id": 22, "quantity": 3 } }, { "id": 23, "name": "Tasty Burger", "description": "...", "created_at": "...", "updated_at": "...", "pivot": { "order_id": 28, "dish_id": 23, "quantity": 1 } } ] }, // ... more orders]
注意事项:
确保正确设置模型之间的关联关系。with() 方法可以预加载多个关联关系,例如 Order::with(‘dishes’, ‘user’)。whereHas() 方法可以嵌套使用,实现更复杂的查询条件。请注意区分用户ID和餐厅ID,避免混淆。
总结
通过使用 Eloquent 的 with() 和 whereHas() 方法,我们可以轻松地获取关联数据,并根据需要进行筛选和分组。这种方法不仅代码简洁,而且效率更高,是处理复杂关联关系的最佳实践。在实际应用中,可以根据具体需求调整查询条件,以获得最佳性能。
以上就是通过 Eloquent 关联模型获取分组数据:以餐厅订单为例的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/20853.html
微信扫一扫
支付宝扫一扫