Laravel withCount() returns null

I need to count the results of Many-to-Many relation subquery.

return $q->withCount(['users' => function($q) {
    $q->select("Users.Id as Id_user","Users.Name");
}])->get()

This code doesn't work. It return null.

However, that works fine and successfully adds users_count column:

return $q->withCount(['users'])->get();

But I need to make select subquery to select specific columns from the relation so I need my first variant get to work.

Thanks a lot!

1 answer

  • answered 2018-11-08 08:48 N69S

    when you use Count or withCount method, the query builder does a select count(id) as aggregate

    if in the condition par of the withCount you override the select part. it breaks

    return $q->withCount(['users' => function($q) {
        //here you are supposed to do condition, not a select
        $q->select("Users.Id as Id_user","Users.Name");
    }])->get()
    

    if you want the id and the name of the user, use with

    return $q->withCount(['users'])
        ->with(['users' => function($q) {
            $q->select("Users.Id as Id_user","Users.Name");
        }])
        ->get()