【发布时间】:2016-06-26 12:36:13
【问题描述】:
这里是我的表迁移(4):
餐厅:
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');
});
如何定义我的 Restaurant、Food、Ingredient 模型及其关系?
这里有一些我需要的例子:
1-所有餐厅的菜肴都含有特定成分。
2-特定餐厅中特定菜肴的所有成分。
3-餐厅中所有使用特定食材的菜肴。
...
--------------编辑后-------- ---------
我有自己的解决方案,但我认为这不是一个好的解决方案。
现在在我的餐厅模型中,我有两个获取食物的实现
一个餐厅的所有食物:
public function foods()
{
return $this->belongsToMany('App\Models\Food', 'restaurant_has_foods_with_ingredients')
->groupBy('food_id');
}
还有一个获取当前餐厅特定食物的成分
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;
}
【问题讨论】:
标签: php laravel laravel-5 laravel-5.2