PinoyStackOverflower
PinoyStackOverflower

Reputation: 5302

cakephp find with count equivalent with this query

SELECT COUNT(*) FROM `users` where usergroup_id = 4 AND studio_id = 380 AND userstatus_id = 1

On this query I am getting a result of 4 which is my expected output, but when doing this query:

$this->User->find('count',array('conditions'=>array(
                                        'User.studio_id'=>380,
                                        'User.usergroup_id'=>4,
                                        'User.userstatus_id'=>1)))

I am getting a result of 8

What do you think is the problem here? Feels like my 2nd code is wrong.

I am a newbie in cakePHP.

Your help would be greatly appreciated and rewarded!

Upvotes: 1

Views: 1897

Answers (1)

Dave
Dave

Reputation: 29121

The query and the CakePHP find('count', ... should produce the same thing. The likely difference (per a few of the comments) is your $recursive level (see CakePHP recursive).

I'm a big fan of just setting:

public $recursive = -1;

in your AppModel - then you don't have to worry about it ever again, as leaving it at -1 is best practice IMO. Then, if you ever want to retrieve additional associated model data, just use CakePHP's Containable.

If you don't want to set it to -1 across the entire site, just set it right before your query:

$this->User->recursive = -1;
$this->User->find('count',array('conditions'=>array(
    'User.studio_id'=>380,
    'User.usergroup_id'=>4,
    'User.userstatus_id'=>1
)));

Site Note: Setting $recursive to ANYTHING other than -1 should be a red flag. It's kind of a cool concept, but in practice, it will cause you many headaches as your site grows. Set it to -1 in the AppModel like suggested above, then forget it even exists.

Upvotes: 1

Related Questions