【问题标题】:Relations in Laravel eloquentLaravel 雄辩的关系
【发布时间】:2020-03-26 06:12:02
【问题描述】:

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

DishValues

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

【问题讨论】:

    标签: php laravel laravel-5


    【解决方案1】:

    鉴于您有多个关系,您可以将 :with() 与值数组一起使用,而不是逗号分隔的字符串。

    这个例子来自docs on "Eager Loading Multiple Relationships",我已经根据你的例子重新命名了模型

    App\Dish::with(['components', 'ingredient'])->get();
    

    还有一篇不错的博文以这种方式探索eager/lazy loading of related models

    【讨论】:

    • 它不工作。我有错误:SQLSTATE [42S22]:找不到列:1054 'where 子句'中的未知列'dishes_id'(SQL:select * from dishes where dishes_id = 2)
    • 按照 laravel 文档中的 Has many through 仔细检查您的架构(迁移)和模型/关系。这表明您的外键可能未在您的模型或迁移中设置或声明正确。
    猜你喜欢
    • 2015-03-14
    • 2018-11-28
    • 2015-01-11
    • 2021-06-03
    • 1970-01-01
    相关资源
    最近更新 更多