在我的雄辩对象中设置一个急切加载函数


Set a eager loading function in my eloquent Object

为了避免重复的代码,我想在我的雄辩模型中创建一个函数eagerLoad()。这是我的代码:

型号产品

public function scopeActive($query)
{
    return $query->where('active', 1);
}
public function eagerLoading($query)
{
    return $query->with([
        'owners',
        'attributes',
        'prices' => function ($query)
        {
            $query->orderBy('created_at', 'desc');
            $query->distinct('type');
        }
    ]);
}

我的控制器

$products = Product::active()->eagerLoading()->paginate(100);
return $this->response->withPaginator($products, $this->productTransformer);

但是当使用它时,我有这个错误:Call to undefined method Illuminate'Database'Query'Builder::eagerLoading()

我应该如何使用我的函数?

您的eagerLoading()方法只是另一个作用域,就像您的scopeActive()方法一样。为了做你想做的事,你需要把它重命名为 scopeEagerLoading() .

现在,Product::active()正在返回一个 Eloquent Query Builder。然后,您尝试对此调用eagerLoading(),并且该方法不存在。通过在方法前面加上 scope 前缀,它告诉查询生成器在它正在查询的模型上调用该方法。

从文档中:
"要定义范围,只需在 Eloquent 模型方法前面加上范围即可。"

在以下位置查看文档: https://laravel.com/docs/5.1/eloquent#query-scopes

因此,您需要重命名方法以在开头具有"范围"。

public function eagerLoading($query)更改为public function scopeEagerLoading($query)