我有一个 many-to-many
关系如下。
public function recipes()
{
return $this->belongsToMany(Recipe::class)->withPivot('number');
}
public function products()
{
return $this->belongsToMany(Product::class)->withPivot('number');
}
我使用的迁移是这样的
Schema::create('product_recipe', function (Blueprint $table) {
$table->unsignedInteger('product_id');
$table->unsignedInteger('recipe_id');
$table->unsignedInteger('number');
$table->primary(['product_id', 'recipe_id']);
});
很标准的东西 每个产品也属于一个类别。在我的视图中,为了将产品添加到配方中,我循环浏览类别和它们的产品,以显示一个漂亮的列表,像这样。
@foreach($categories as $category)
// Display $category information
@foreach($category->products as $product)
// Display product name and a select menu for the number
@endforeach
@endforeach
我唯一的问题是,当我稍后为食谱编辑这个列表时, 我不能在数字选择菜单中选择数字。实际上,我可以,我在我的产品模型中使用了这个方法。
public function getNumber($recipe_id)
{
return DB::table('recipe_product')
->whereProductId($this->id)
->whereRecipeId($recipe_id)
->value('number');
}
但我相信不是这样做的 一定有更好的方法来完成这个任务的。
withPivot()
允许你通过父模型检索所有你要求的列,如 $parent->pivot->some_column
你可能正在寻找这样的东西。
@foreach($category->products as $product)
// ...
<select name="quantity">
@for($i = 0; $i < 123; $i++)
<option value="{{ $i }}"{{ $i == $product->pivot->number ? ' selected' : '' }}>{{ $i }}</option>
@endfor
</select>
@endforeach