laravel 在整数上调用成员函数 addEagerConstraints()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43898167/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 15:56:40  来源:igfitidea点击:

Call to a member function addEagerConstraints() on integer

laraveleloquenteager-loading

提问by Juliatzin

I tried to eager load a relation:

我试图急切地加载一个关系:

$tournaments = Tournament::with('numCompetitors')->latest()->paginate(config('constants.PAGINATION'));

My relation in Tournament returns an integer:

我在锦标赛中的关系返回一个整数:

public function numCompetitors()
{
    return $this->competitors()->count(); // it returns 24
}

With that I get:

我得到:

Call to a member function addEagerConstraints() on integer

I don't understand why is it failing.

我不明白为什么它失败了。

回答by Alexey Mezenin

You're doing it wrong. If you want to count relationship, use withCount()with properly defined relationship:

你这样做是错的。如果要计算关系,请使用withCount()正确定义的关系:

Tournament::withCount('competitors')->latest()->paginate(config('constants.PAGINATION'));

If you want to count the number of results from a relationship without actually loading them you may use the withCount method, which will place a {relation}_countcolumn on your resulting models.

如果您想计算关系中的结果数量而不实际加载它们,您可以使用 withCount 方法,它将{relation}_count在您的结果模型上放置一列。

https://laravel.com/docs/5.4/eloquent-relationships#counting-related-models

https://laravel.com/docs/5.4/eloquent-relationships#counting-related-models