【问题标题】:laravel 5.7 correct way of getting results on many to many relationlaravel 5.7 获得多对多关系结果的正确方法
【发布时间】:2019-05-22 03:54:33
【问题描述】:

我正在学习 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”。然后,我必须获取每种食物、它们的成分,以及每种成分的过敏原。所以,我想从现在开始做好。

提前谢谢你。

【问题讨论】:

  • $food->ingredients 包含一个集合中所有与食物相关的成分。您需要另一个 foreach 循环,如下所示:foreach($food->ingredients as $ingredient ) $ingredient->name

标签: laravel many-to-many pivot-table


【解决方案1】:

食物模型

  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 是数据透视表名称

【讨论】:

    猜你喜欢
    • 2017-10-03
    • 2019-06-03
    • 2019-08-17
    • 2017-03-27
    • 2019-12-30
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 2019-03-10
    相关资源
    最近更新 更多