Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call to a member function addEagerConstraints() on integer

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.

like image 745
Juliatzin Avatar asked May 10 '17 16:05

Juliatzin


1 Answers

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

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

like image 86
Alexey Mezenin Avatar answered Nov 12 '22 19:11

Alexey Mezenin