
本文旨在提供一种使用 Laravel Eloquent ORM 通过关联模型获取并分组数据的有效方法。我们将以餐厅、菜品和订单之间的关系为例,展示如何使用 with() 和 whereHas() 方法,避免使用循环,从而编写更简洁、更高效的代码。通过本文,你将学会如何根据订单 ID 对结果进行分组,并获得包含菜品及其数量的结构化数据。
在 Laravel 应用中,经常需要通过关联关系获取数据。例如,在一个餐厅应用中,一个餐厅可以有多个菜品,一个菜品可以属于多个订单,一个订单可以包含多个菜品。
假设我们有三个模型:Restaurant(餐厅)、Dish(菜品)和 Order(订单)。它们之间的关系如下:
以下是模型的定义:
// 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');
}
}为了获取特定餐厅的所有订单,并按照订单 ID 分组,我们可以使用 with() 和 whereHas() 方法,避免使用循环,提高查询效率。
以下是查询的代码示例:
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);
}代码解释:
返回结果示例:
上述代码将返回一个 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
]注意事项:
通过使用 Eloquent 的 with() 和 whereHas() 方法,我们可以轻松地获取关联数据,并根据需要进行筛选和分组。这种方法不仅代码简洁,而且效率更高,是处理复杂关联关系的最佳实践。在实际应用中,可以根据具体需求调整查询条件,以获得最佳性能。
以上就是通过 Eloquent 关联模型获取分组数据:以餐厅订单为例的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号