【问题标题】:Laravel sub-relationshipLaravel 子关系
【发布时间】:2019-02-18 22:40:59
【问题描述】:

我有以下型号:

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

【问题讨论】:

    标签: laravel laravel-5 eloquent


    【解决方案1】:

    你必须使用

    belongsTo 这样的方法:

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

    【讨论】:

      【解决方案2】:

      这个怎么样:

      return Recipe::with('parts.ingredients')
          ->with('parts.ingredients.ingredient')
          ->find($request->id);
      

      【讨论】:

        猜你喜欢
        • 2020-02-20
        • 1970-01-01
        • 2020-03-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多