cakephpcakephp-2.6

CakePHP: Egregious amount of calls to SELECT count(*)


CakePHP makes this exact query three times:

SELECT COUNT(*) AS `count` FROM `mydb`.`players` AS `Player` WHERE `Player`.`id` = 8

When I run:

$this->Player->id = $player_id;
$this->Player->save($save_array);

It seems CakePHP does this to check if a Model->save() should be a create or update entry. I've looked into the issue and have tried to implement the following:

Force CakePHP to do an update by providing the ID key in the saveFields. I thought it would not need to do a COUNT(*) if it knew to update every time. That's my real goal, here: something like updateAll that works as save() does. Supposing updateAll doesn't make this COUNT(*) as well.

Custom paginate, I either did it wrong or it wasn't the problem.

Changing the model.php(!) was dangerous and ultimately unsuccessful.

I just want to have another function like save() that simply updates, so that I can be rid of these COUNT(*) queries, but I'm not sure CakePHP supports such a thing.


Solution

  • The calls come from the Model::exists() function in the model. You can override that function in your AppModel, or any model where you need to prevent this and locally cache the result of the function.

    For example, if it gets the id = 8 in that function you can have an array remembering that this id already exists.