首页 > 解决方案 > Laravel 子关系

问题描述

我有以下型号:

class Recipe extends Model
{

    public function parts() {
        return $this->hasMany('App\RecipePart');
    }
}

class Ingredient extends Model
{
    protected $fillable = [
            'name','image'
        ];
}

class RecipePart extends Model
{
    public $timestamps = false;

    public function ingredients()
    {
        return $this->hasMany('App\RecipePartIngredient');
    }
}

在我的控制器中,我想返回一个所有配方部分都属于他的配方,所有成分都属于每个配方部分。以下代码有效,但是...:

return Recipe::with('parts.ingredients')
            ->where('id',$request->id)->first();

它有效,我parts.ingredients返回recipe_part_ingredients表中的数据,这没关系,但我想要每个成分 ID - 从我的ingredients表中返回成分信息。(名称,图像)。

知道我该怎么做吗?我尝试将以下代码添加到我的 RecipePartIngredient,但没有运气:

public function ingredient() {
        return $this->hasOne('App\Ingredient');
    }

标签: laravellaravel-5eloquent

解决方案


你必须使用

像这样的 belongsTo方法:

public function ingredient() {
    return $this->belongsTo('App\Ingredient');
}

推荐阅读