Framework: Query Builder withCount not available when using select

Created on 25 Sep 2016  路  2Comments  路  Source: laravel/framework

  • Laravel Version: 5.3.1
  • PHP Version: 7.0.10
  • Database Driver & Version: mysql 5.6.28

    Description:

I have the following code to get some specific events (Events of Clubs that a user has liked)

$events = Event::query();

$events->with('club');
$events->with('hasUserTicket');
$events->with('hasUserGuestlist');

$events->withCount('tickets');
$events->withCount('guestlist');

$events->join('clubs', 'clubs.id', '=', 'events.club_id');
$events->join('likeables', 'likeables.likeable_id', '=', 'clubs.id');
$events->join('users', 'users.id', '=', 'likeables.user_id');

$events->select('clubs.*', 'clubs.name as clubs.name', 'events.*');

$events->where('likeables.likeable_type', 'App\\Club');
$events->where('users.id', $user->id);
$events->orderBy('events.date', 'ASC');

return $events->get();

My problem is, that because of the line _$events->select.._. the two columns tickets_count & guestlist_count (from _->withCount('guestlist');_ & _->withCount('tickets');_) are missing in the result.

Is that expected behaviour? Because the values of hasUserTicket and hasUserGuestlist are available in the result. Or do I need to explicitly call the two properties in the select method and if so, how?

Most helpful comment

Okay, so I figured out that it works when I put withCount after the select method

            ->select('clubs.*', 'clubs.name as clubs.name', 'events.*')
            ->withCount('tickets')
            ->withCount('guestlist')

Strange (to me) but good that it works!

All 2 comments

Okay, so I figured out that it works when I put withCount after the select method

            ->select('clubs.*', 'clubs.name as clubs.name', 'events.*')
            ->withCount('tickets')
            ->withCount('guestlist')

Strange (to me) but good that it works!

When encapsulating the withCount in a function within a EloquentModel we need to use the select after the encapsulated function as the select return QueryBuilder so not sure how to solve that yet

Was this page helpful?
0 / 5 - 0 ratings

Related issues

lzp819739483 picture lzp819739483  路  3Comments

ghost picture ghost  路  3Comments

iivanov2 picture iivanov2  路  3Comments

gabriellimo picture gabriellimo  路  3Comments

PhiloNL picture PhiloNL  路  3Comments