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

Call to a member function addEagerConstraints() on integer

我试图加载关系:

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

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

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

这样我得到:

Call to a member function addEagerConstraints() on integer

我不明白为什么会失败。

你做错了。如果你想计算关系,请使用 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}_count column on your resulting models.

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