我是Laravel的初学者。我在我的项目Laravel 5.8中使用。
我有此代码:
Dish.php
class Dish extends Model
{
protected $quarded = ['id'];
protected $fillable = ['company_id', 'name', 'description', 'enable'];
public $timestamps = false;
public function components()
{
return $this->hasManyThrough('App\DishValues', 'App\Dish', 'id', 'dishes_id');
}
}
菜肴价值
class DishValues extends Model
{
protected $quarded = ['id'];
protected $fillable = ['dishes_id', 'food_ingredient_id', 'quantity'];
public $timestamps = false;
public function ingredient()
{
return $this->belongsTo('App\FoodIngredient', 'food_ingredient_id');
}
}
FoodIngredient.php
class FoodIngredient extends Model
{
use scopeActiveTrait;
public function scopeVisibleDemo($query)
{
return $query->where('available_in_demo', 1);
}
protected $quarded = ['id'];
protected $fillable = ['company_id', 'name', 'garbage', 'energy_value', 'protein', 'fat', 'available_carbohydrates', 'roughage', 'description', 'url_address', 'allergen', 'available_in_demo', 'enable'];
public $timestamps = false;
}
我得到了我的数据:
Dish::with('components')->paginate(25);
如何从FoodIngredient获取此代码值?
这不起作用:
Dish::with('components, ingredient')->paginate(25);
或
Dish::with('components')->with('ingredient')->paginate(25);
答案 0 :(得分:1)
鉴于您具有多个关系,因此您可以将:with()
与值数组(而不是逗号分隔的字符串)一起使用。
此示例来自docs on "Eager Loading Multiple Relationships",我根据您的示例重命名了模型
App\Dish::with(['components', 'ingredient'])->get();
还有一篇不错的博客文章,以这种方式探索eager/lazy loading of related models。