通过 Eloquent 关联模型获取分组数据:以餐厅订单为例

DDD
发布: 2025-10-08 09:49:08
原创
996人浏览过

通过 eloquent 关联模型获取分组数据:以餐厅订单为例

本文旨在提供一种使用 Laravel Eloquent ORM 通过关联模型获取并分组数据的有效方法。我们将以餐厅、菜品和订单之间的关系为例,展示如何使用 with() 和 whereHas() 方法,避免使用循环,从而编写更简洁、更高效的代码。通过本文,你将学会如何根据订单 ID 对结果进行分组,并获得包含菜品及其数量的结构化数据。

利用 Eloquent 关联关系获取数据

在 Laravel 应用中,经常需要通过关联关系获取数据。例如,在一个餐厅应用中,一个餐厅可以有多个菜品,一个菜品可以属于多个订单,一个订单可以包含多个菜品。

假设我们有三个模型:Restaurant(餐厅)、Dish(菜品)和 Order(订单)。它们之间的关系如下:

  • Restaurant has many Dish
  • Dish belongs to many Restaurant
  • Dish belongs to many Order with pivot quantity
  • Order belongs to many Dish

以下是模型的定义:

// Restaurant 模型
class Restaurant extends Authenticatable
{
    public function dishes()
    {
        return $this->belongsToMany('App\Models\Dish');
    }
}

// Dish 模型
class Dish extends Model
{
    public function orders()
    {
        return $this->belongsToMany('App\Models\Order')->withPivot('quantity');
    }

    public function restaurant()
    {
        return $this->belongsToMany('App\Models\Restaurant');
    }
}

// Order 模型
class Order extends Model
{
    public function dishes()
    {
        return $this->belongsToMany('App\Models\Dish')->withPivot('quantity');
    }
}
登录后复制

使用 with() 和 whereHas() 进行高效查询

为了获取特定餐厅的所有订单,并按照订单 ID 分组,我们可以使用 with() 和 whereHas() 方法,避免使用循环,提高查询效率。

以下是查询的代码示例:

云雀语言模型
云雀语言模型

云雀是一款由字节跳动研发的语言模型,通过便捷的自然语言交互,能够高效的完成互动对话

云雀语言模型 54
查看详情 云雀语言模型
use App\Models\Order;
use Illuminate\Database\Eloquent\Builder;

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);
}
登录后复制

代码解释:

  1. Order::with('dishes'):使用 with() 方法预加载订单关联的菜品,减少 N+1 查询问题。
  2. ->whereHas('dishes', ...):使用 whereHas() 方法筛选包含指定餐厅菜品的订单。
  3. function (Builder $dishes) use ($restaurant_id) { ... }:在 whereHas() 方法中使用闭包,以便访问外部变量 $restaurant_id。
  4. $dishes->where('restaurant_id', $restaurant_id):在闭包中,筛选菜品表中 restaurant_id 等于指定餐厅 ID 的菜品。
  5. ->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 关联模型获取分组数据:以餐厅订单为例的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
热门推荐
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号