dimanche 17 février 2019

Laravel sub-relationship

I have the following models:

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

In my controller, I want to return a recipe with all recipe parts belongs to him, and all ingredients belong to each recipe part. The following code works, but...:

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

It works, my parts.ingredients returns the data in my recipe_part_ingredients table, which is OK, but I want for each ingredient_id - return the ingredient information from my ingredients table. (name, image).

Any idea how I can do this? I tried to add the following code to my RecipePartIngredient, but no luck:

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



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire