1

I have a User model and a Message model.

The Message model is linked to the User model twice like this:

public $belongsTo = array(
    'UserSender' => array(
        'className' => 'User',
        'foreignKey' => 'sender_id',
        'counterCache' => array(
            'messages_sent_count' => array(
                'is_deleted' => FALSE
            )
        )
    ),
    'UserRecipient' => array(
        'className' => 'User',
        'foreignKey' => 'recipient_id',
        'counterCache' => array(
            'messages_received_count' => array(
                'is_deleted' => FALSE
            ),
            'messages_unread_count' => array(
                'is_deleted' => FALSE,
                'is_read' => FALSE
            )
        )
    ),
    'Operator' => array(
        'className' => 'Operator',
        'foreignKey' => 'operator_id'
    )
);

Besides the User model, the Message model also $belongsTo the Operator model. The Operator model is irrelevant to the message count for the users, but its table is still being joined in the count query, as debug shows:

'query' => 'SELECT COUNT(*) AS `count` FROM `database`.`messages` AS  `Message` LEFT JOIN `database`.`operators` AS `Operator` ON (`Message`.`operator_id` = `Operator`.`id`) LEFT JOIN `database`.`users` AS `UserSender` ON (`Message`.`sender_id` = `UserSender`.`id`) LEFT JOIN `database`.`users` AS `UserRecipient` ON (`Message`.`recipient_id` = `UserRecipient`.`id`)  WHERE `Message`.`is_deleted` = '0' AND `Message`.`sender_id` = 389',
        'params' => array(),
        'affected' => (int) 1,
        'numRows' => (int) 1,
        'took' => (float) 394

For the sake of simplicity I've actually excluded one more model that the Message model $belongsTo, but the above query shows the problem.

The counterCache function does a quite expensive query just to update the counter. Is there a way to maybe override or adjust the counterCache method to not join irrelevant tables in the query?

2
  • this query doesn't update the counter.and hwo are you defining the counterCache? it is suppose to be boolean in cake 2.x. Aug 1, 2014 at 10:03
  • You're right. The next query in the log actually updates the counter. But this SELECT query is actually the problem, because it joins tables that don't need to be selected for the update. The counterCache counts the messages based on the criteria defined in the counterScope (is_read, is_deleted, etc) and writes them to the user table.
    – Botch
    Aug 1, 2014 at 14:23

1 Answer 1

3

I can't test it right now, but since the recursive setting used by Model::updateCounterCache() is hard-coded based on whether conditions are defined for the counter cache field, the only way to change this (besides completely reimplementing Model::updateCounterCache()) is probably to modify the count query in Model::_findCount() or Model::beforeFind() of your Message model.

public function beforeFind($query) {
    // ... figure whether this is the count query for updateCounterCache,
    // maybe even try to analyze whether the passed conditions require
    // joins or not.

    if(/* ... */) {
        $query['recursive'] = -1;
    }

    return $query;
}

Depending on how much control you'll actually need the containable behavior might do the trick too, it sets recursive to -1 in case no containments are being passed

$Message->contain(); // === recursive is being set to -1 in before find callback
$Message->delete(123);
3
  • I eventually went with the following: public function beforeFind($query) { if($query['fields'] == "COUNT() AS 'count'") { $query['recursive'] = -1; } } And it works fine. The only drawback, which is not that serious is that I can't use 'fields' => "COUNT() AS 'count'" in my own find queries with recursion. But I guess if I wanted to I could use "COUNT(*) AS count" (without the other quotation marks) and it would still work.
    – Botch
    Aug 5, 2014 at 7:35
  • There is a serious problem with the solution I provided above. It breaks the pagination, because pagination uses the same value for 'fields' to build the paginator.
    – Botch
    Aug 12, 2014 at 20:51
  • I ended up writing custom counters. I advise against using counterCache at all when dealing with large tables and queries that are performed often. See, each time an action is performed it has to count all the rows in the table. For example, if you have more than a million records in a table (messages) and a COUNT(*) has to be performed each time a record is added or updated, it might take a couple of seconds to update the counter for a specific user. I ended up writing a simple increase/decrease function to update the count in afterSave() for the relevant user.
    – Botch
    Aug 12, 2014 at 20:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.