我在处理模型和数据透视时遇到了 n+1 个查询
Recipe.php:
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
public function ingredients(): BelongsToMany
{
return $this->belongsToMany(Ingredient::class)
->using(IngredientRecipe::class)
->withTimestamps()
->withPivot(['quantity', 'unit_id']);
}
IngredientRecipe.php(数据透视表):
public function unit(): BelongsTo
{
return $this->belongsTo(Unit::class);
}
成分.php:
public function recipes(): BelongsToMany
{
return $this->belongsToMany(Recipe::class);
}
单元.php:
public function ingredient_recipes(): HasMany
{
return $this->hasMany(IngredientRecipe::class);
}
我想做什么:
在我的用户资料页面中,我想显示所有者(用户)的食谱列表。每个食谱ingredients()
都包含在数据透视表中,并带有附加列quantity
,以及unit_id
代码:
在我的ProfileController.php
我正在使用这个代码:
public function show_profile(User $user)
{
$userRecipes = $user->recipes()->with('ingredients', 'guideSteps')->get();
return view('user.user-profile', compact('user', 'userRecipes'));
}
问题:
Laravel 不知道这pivot->unit_id
与模型有关Unit
,所以每次我访问时pivot->unit
,它都会对表进行单独的查询units
。
在调试栏中我收到15 个重复的查询:
users
从其中选择 * users
。id
= 1 限制 1
units
从其中选择 * units
。id
= 3 限制 1
units
从其中选择 * units
。id
= 3 限制 1
...另外 12 个
问题就出在这个地方:
@foreach($userRecipes as $recipe)
<x-recipe-card :recipe="$recipe"/>
@endforeach
---------------inside component recipe-card:------------------------
@foreach($recipe->ingredients as $ingredient)
<div>
<span>{{ $ingredient->name }}</span>
<div></div>
<span>{{ $ingredient->pivot->quantity . ' '. $ingredient->pivot->unit->name}}</span>
</div>
@endforeach
Laravel 不会自动预先加载在枢轴模型内定义的关系。
尝试这样的方法(未测试)
编辑 02