Although I’m aware of the group, contain, fields and order options on a find(), I just cannot seem to make the following query with CakePHP 2.2.3 :
SELECT `User`.*, SUM(`Influence`.`id`) AS matches
FROM `db`.`users` AS `User`
LEFT JOIN `db`.`influences_users` AS `InfluencesUser` ON (`User`.`id` = `InfluencesUser`.`user_id`)
LEFT JOIN `db`.`influences` AS `Influence` ON (`InfluencesUser`.`influence_id` = `Influence`.`id`)
WHERE 1 = 1
AND `Influence`.`id` IN (1, 2, 3, 4)
GROUP BY `User`.`id`
ORDER BY COUNT(`Influence`.`id`) DESC
Basically, I’m trying to retrieve an array of Users having the Influences 1, 2, 3 and 4, with the COUNT() function on the Influences tables, then order them by COUNT() DESC.
Is there a clean way (I’d rather not want to use any hacks or functions like Model::query()) to do so in CakePHP?
EDIT: It wasn’t actually a SUM() but rather a COUNT() although I doesn’t change anything to my problem.
I managed to find a solution, not too hacky and unless someone has a better solution (not a lot when you see the number of answers I got), here it is:
I manually join the
InfluencesUsertable (I don’t actually need theInfluenceone, only the list ofinfluence_id) to make a big table. I just had to do the restriction (influence_id) on thejointable, then I can do mygoup by, thecount()and append thecount()field to my results array, thanks to mark’s answer.Obviously I would have prefered using something like the
containparameter, but it doesn’t seem to allow me to do what I can achieve with thejoinin this particular situation.Hope this could save some time to some people.