简体   繁体   English

laravel中的多对多关系

[英]Many to Many to Many relation in laravel

Here my tables migrations(4): 这是我的表迁移(4):

restaurants: 餐馆:

Schema::create('restaurants', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
});

foods: 食物:

Schema::create('foods', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
});

ingredients: 配料:

Schema::create('ingredients', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
});

restaurant_has_foods_with_ingredients: 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');
});

How can I define my Restaurant,Food,Ingredient Models with their relations? 如何定义餐厅,食品,成分模型及其关系?

Here some examples of my needs: 这里有一些我需要的例子:

1-All restaurants with specific ingredient in their serving dishes. 1-所有餐厅在其菜式中均包含特定成分的餐厅。

2-All ingredients of a specific dish in a specific restaurant. 2-特定餐厅中特定菜肴的所有成分。

3-All dishes with a specific ingredient in a restaurant. 3-在餐厅中所有具有特定成分的菜肴。

... ...

-------------------------After Edit----------------------------- -------------------------编辑后--------------------------- ------

I have my own solution but I think it's not a good one. 我有自己的解决方案,但我认为这不是一个好方法。

Now in my Restaurant model I have two implementation of getting food 现在在我的餐厅模型中,我有两种实现食物获取的方法

One to get all foods of a restaurant: 一个获得所有餐厅食物的人:

public function foods()
{
    return $this->belongsToMany('App\Models\Food', 'restaurant_has_foods_with_ingredients')
        ->groupBy('food_id');
}

And another one to get ingredients of current restaurunt's specific food 另一种用于获取当前餐厅特定食物的成分

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;
}

Basicly its something like this : 基本上是这样的:

Create two migration : restaurant_food and food_ingredient 创建两个迁移: restaurant_foodfood_ingredient

we have a 我们有一个

Restaurant model - Food model - ingredient model 餐厅模型-食品模型-配料模型

A Restaurent can have many types of food and a food can be in served restaurent -> so we have a many to many relation here 餐馆可以有多种食物,而食物可以在餐馆中食用->因此,我们在这里有多对多关系

Restaurant model 餐厅模型

class Restaurant extends Model
{
    /**
     * The foods that belong to the Restaurant.
     */
    public function foods()
    {
        return $this->belongsToMany('App\Food');
    }

}

Alright now with the next thing 现在,接下来的事情

1- As we mentioned before , a food type can be served in many restaurants so we need to define the inverse relation. 1-如前所述,许多餐馆都可以提供食物类型,因此我们需要定义反比关系。

2- A food has many ingredients and an ingredient can be used in many types of food -> Another many to many 2-一种食物具有多种成分,并且一种成分可以用于多种类型的食物->另一种多对多

Food model 食物模型

class Food extends Model
{
     /**
     * The ingredients that belong to the Food.
     */
    public function restaurants()
    {
        return $this->belongsToMany('App\Restaurant');
    }
    /**
     * The ingredients that belong to the Food.
     */
    public function ingredients()
    {
        return $this->belongsToMany('App\Ingredient');
    }

}

Now the same goes for 现在也一样

Ingredient model 成分模型

class Ingredient extends Model
{
    /**
     * The foods that belong to the Ingredient.
     */
    public function foods()
    {
        return $this->belongsToMany('App\Food');
    }

}

Alright now we have everything setup this is how it's used 好了,我们已经完成了所有设置,这就是它的用法

Adding to a relation 添加到关系

$Restaurant = Restaurant::find($id);
$Restaurant->foods()->attach($food_id);

Removing from a relation 从关系中删除

$Restaurant->foods()->detach($food_id);

1-All restaurants with specific ingredient in their serving dishes. 1-所有餐厅在其菜式中均包含特定成分的餐厅。

$restaurants = App\Restaurant::with(['foods' => function ($query) {
    $query->whereHas(['ingredients' => function ($query) {
      $query->where('name', 'like', 'potato');

}])->get();

2-All ingredients of a specific dish in a specific restaurant. 2-特定餐厅中特定菜肴的所有成分。

$ingridients = App\Ingredient::whereHas(['foods' => function ($query) {
    $query->where('name', 'like', 'potato')->whereHas(['restaurant' => function ($query) {
      $query->where('name', 'like', 'newyork');

}])->get();

3-All dishes with a specific ingredient in a restaurant. 3-在餐厅中所有具有特定成分的菜肴。

$foods= App\Food::whereHas(['ingredients' => function ($query) {
    $query->where('name', 'like', 'potato');
},
'restaurants' => function ($query) {
        $query->where('name', 'like', 'newyork');
   }
])->get();

change potato/newyork with a variable and you are good to go 用变量改变马铃薯/纽约,你很高兴

My code might have some minor typos or mistakes but i hope you got the idea of how things work 我的代码可能有一些小错别字或错误,但我希望您对事情的运作方式有所了解

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM