lundi 26 décembre 2016

Getting the count of a constrained, joined query in Laravel's query builder

I have a one-to-one relationship between users and activities, such that each user has a last_activity_id which maps to a particular row in activities.

I need to be able to filter a list of users based on the value of a column in their last activity. To be able to do additional things like pagination, this must be done in the query itself, so I cannot fetch the results and then apply the filters after the fact. Thus, I use a select along with a leftJoin to bring the related columns directly into my result set:

$query = User::select(
            'users.*',
            'activities.description as last_activity_description')
         ->leftJoin('activities', 'activities.id', '=', 'users.last_activity_id')
         ->having('last_activity_description', 'like', "%blanchin%");

This seems to work fine, and I can call $query->get() to get the filtered result set. It generates a query that looks like:

select `users`.*, 
    `activities`.`description` as `last_activity_description` 
from `users` 
left join `activities` on `activities`.`id` = `users`.`last_activity_id`
having `last_activity_description` like '%blanchin%'

However, if I try to then get a count on this result set by calling $query->count(), Laravel generates this (failed) query:

select count(*) as aggregate 
from `users` 
left join `activities` on `activities`.`id` = `users`.`last_activity_id` 
having `last_activity_description` like '%blanchin%'

It seems that calling count() has stripped out my original select clause and replaced it with select count(*) as aggregate, which means that my having clause fails because the last_activity_description alias is no longer defined.

How can I work around this?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire