首页 > 解决方案 > laravel 5.7 获得多对多关系结果的正确方法

问题描述

我正在学习 laravel 框架,我有一个非常简单的问题:

我有三张桌子:

食物表:

foods
--------------
id | name

成分表:

ingredients
---------------
id, | name

数据透视表:

food_ingredient
---------------
food_id | ingredient_id

在模型中,我有“belongsToMany”方法:

食品型号:

public function ingredients(){
    return $this->belongsToMany('App\Models\Ingredient');
}

成分型号:

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

FoodsController(索引):

    $foods = Food::all();

    foreach($foods as $food){
        $food->ingredients = Ingredient::join('food_ingredient','food_ingredient.id','=','ingredients.id')
                                       ->where('food_ingredient.food_id',$food->id)->get();
    }

我想获取每种食物的成分信息(直到现在只是名称),这个查询(那个在 foreach 循环中)可以做到,但我不确定我是否以正确的方式做。我没有使用belongsToMany 关系所以......我的理解一定有问题。

我怎样才能得到成分的名称?

直到知道这些名字都可以,但我会添加第三个表“过敏原”,它很快就会成为数据透视表“allergen_ingredient”。然后,我必须得到每种食物、它们的成分,以及每种成分的过敏原。所以,我想从现在开始做好。

先感谢您。

标签: laravelmany-to-manypivot-table

解决方案


食物模型

  class Food extends Model
{
    protected $table        = 'foods';
    protected $primaryKey   = 'food_id';
    public    $incrementing = TRUE;
    public    $timestamps   = FALSE;
    protected $fillable     = [
        'food_name'
    ];
    public
    function ingredients()
    {
        return $this->belongsToMany(Ingredient::class, 'food_ingredients', 'food_id', 'ingredient_id');
    }
}

成分模型

class Ingredient extends Model
{
    protected $table        = 'ingredients';
    protected $primaryKey   = 'ingredient_id';
    public    $incrementing = TRUE;
    public    $timestamps   = FALSE;
    protected $fillable     = [
        'ingredient_name'
    ];


    public
    function foods()
    {
        return $this->belongsToMany(Food::class, 'food_ingredients', 'ingredient_id', 'food_id');
    }
}

你可以这样称呼它:

$foods = Food::all();
   foreach( $foods as $food )
   {
       foreach( $food->ingredients as $ingredient )
       {
         echo $ingredient->ingredient_name . " <br>";
       }
   }

food_ingredients 是数据透视表名称


推荐阅读