In Laravel 4, we do not have the method present in Laravel 5.2 > = called withCount
. This withCount
is responsible for adding to the SELECT
the count of items related to the current entity.
For example:
$u = Usuario::withCount('posts')->first();
var_dump($u->posts_count); // int(5)
But in my case, I'm maintaining a system I did some 3 years ago, where I still used Laravel 4. And the solution we had at the time, without writing SQL in hand, was to call a count
for each related item.
So:
foreach($usuarios as $usuario) {
echo $usuario->posts()->count();
}
The problem with this is that, for each iteration, Laravel will call a SELECT COUNT(*) FROM posts WHERE usuario_id = ?
, and I imagine that in an iteration of 500 rows, this will screw up my database server.
And in my case, I also believe that it is impracticable to migrate the project from Laravel 4 to 5.
So, I ask:
- How can I load (eager loader) the count of items related to an entity (model) in Laravel 4?