Question

I have the following virtual field on my Page model

function __construct($id = false, $table = null, $ds = null) {
    $this->virtualFields['fans'] = 'SELECT COUNT(Favorite.id) FROM favorites AS Favorite WHERE Favorite.page_id = Page.id AND Favorite.status = 0';
    parent::__construct($id, $table, $ds);
}

This works as expected and displays the number of users who have added the page to their favorites. The issue is that, during development, some rows have duplicate user_id to page_id pairs so it returns the incorrect number or unique users. I tried adding a group by clause like so

$this->virtualFields['fans'] = 'SELECT COUNT(Favorite.id) FROM favorites AS Favorite WHERE Favorite.page_id = Page.id AND Favorite.status = 0 GROUP BY Favorite.user_id';

But it does not work. I tried debugging the issue but I receive the error message "allowed memory size exhausted". I also tried using SELECT COUNT('Favorite.user_id') and SELECT DISTINCT('Favorite.user_id') neither of which worked either. I believe DISTINCT is further away from the answer as that would return an array (I believe?)

Is this a known CakePHP issue? Am I implementing the group by wrong? Is there another solution to do this other than afterfind?

Was it helpful?

Solution

try this

    SELECT COUNT(DISTINCT Favorite.user_id)

like that :

 $this->virtualFields['fans'] = 'SELECT COUNT(DISTINCT id) FROM favorites  WHERE  status = 0';
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top