这里我表迁移(4):多对多在laravel许多关系
餐馆:
Schema::create('restaurants', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
});
食物:
Schema::create('foods', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
});
成分:
Schema::create('ingredients', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
});
restaurant_has_foods_with_ingredients:
Schema::create('restaurant_has_foods_with_ingredients', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('restaurant_id');
$table->unsignedInteger('food_id');
$table->unsignedInteger('ingredient_id');
$table->foreign('restaurant_id')
->references('id')
->on('restaurants')
->onDelete('cascade');
$table->foreign('food_id')
->references('id')
->on('foods')
->onDelete('cascade');
$table->foreign('ingredient_id')
->references('id')
->on('ingredients')
->onDelete('cascade');
});
如何定义我的餐厅,食品,配料模型及其关系?
这里我需要一些例子:
1,所有餐馆在他们的餐盘的具体成分。
2-在特定餐厅的特定菜肴的所有成分。
3 - 所有菜肴在餐厅的特定成分。
...
-------------------------编辑后------------ -----------------
我有我自己的解决方案,但我认为这不是一个好的。
现在在我的餐厅模式,我有两种实现获取食物
一拿到餐厅所有的食物:
public function foods()
{
return $this->belongsToMany('App\Models\Food', 'restaurant_has_foods_with_ingredients')
->groupBy('food_id');
}
而另一个得到的电流restaurunt的具体食品配料
public function foodIngredients(Food $food)
{
$result = DB::table('restaurant_has_foods_with_ingredients')
->select('restaurant_has_foods_with_ingredients.ingredient_id as ingredient_id')
->where('restaurant_has_foods_with_ingredients.restaurant_id',$this->id)
->where('restaurant_has_foods_with_ingredients.food_id',$food->id)
->get();
$ingredients = array();
foreach ($result as $row) {
$ingredients[] = Ingredient::find($row->ingredient_id);
}
return $ingredients;
}
谢谢您的出色答案,但问题在这里: 两家餐厅的同一道菜有不同的配料(不同餐厅的料理可能不同) –
你应该提到,起初,生病尝试和编辑 –
你能否提供我一个预期的例子结果,所以我可以解决并尝试如何实现它? –