Note: I originally asked this question about an hour ago but only recently realized I had made a major copy and paste mistake. One so significant that it was easier to delete the old post and start over. Sorry about that.
In the CakePHP framework, after I updated a Model, I dumped the SQL queries. COUNT(*) is called twice, for no apparent reason.
So I have two Models, $Foo and $Bar. For simplicity sake, I have not defined any $belongsTo or $hasMany relationships between them. The problem only involves $Foo, but just in case I’ve included $Bar’s code as well.
$data = array(
'something' => 12,
'something_else' => $this->Bar->field('id', $conditions),
);
$this->Foo->id = $this->Foo->field($data);
$this->Foo->save($data);
I am getting the $Bar.id field according to a set of conditions (which aren’t relevant here). I use that id to determine the $data that should INSERT or UPDATE into $Foo. If $Foo has an id that fulfills $data‘s requirements that value will be returned; if not false will be returned. According to CakePHP’s architecture, save() will UPDATE if there’s a valid id; otherwise it will INSERT. I’m pretty sure I’m not doing anything unusual.
Here’s what I see in the SQL dump:
SELECT `Foo`.`id` FROM `foos` AS `Foo` WHERE `something` = 12 AND `something_else` = 1 LIMIT 1
SELECT COUNT(*) AS `count` FROM `foos` AS `Foo` WHERE `Foo`.`id` = 1
SELECT COUNT(*) AS `count` FROM `foos` AS `Foo` WHERE `Foo`.`id` = 1
UPDATE `foos` SET `something` = 12, something_else` = 1 WHERE `foos`.`id` = 1'
For the life of me I can’t figure out why COUNT() is needed at all, much less why it’s called twice. Does anyone have an idea of what’s going on? Thanks for the help.
I haven’t worked with CakePHP, but looking at the source code here, you’ll see in the field function that it calls the find method.
Therefore, this call
Generates:
Then the set field call
generates this through the inner find function call:
The Save function also calls find to see if the record exists before saving, which generates the second call:
The final query is the obvious save itself.
Please look for yourself to verify I’m reading it correctly, but that’s what it appears to do.