User Profile
- User
- dericknwq
- Location
- Singapore
- Time Zone
- URL
- http://derick.lyniq.com
Recent Articles
counterCache or counter_cache Behavior
I wrote this because I needed something simple for my recent project and CakePHP have not implemented the counterCache option yet. This is my first time writing a Behavior and largely based on http://groups.google.com/group/cake-php/msg/74508dad38d3d623 but it doesn't work for me though. You may wish to learn more about why counterCache is useful at http://groups.google.com/group/cake-php/msg/971ced72abe96b03
- Published by dericknwq 05/02/07 - 05:01
- 15790 views
- 8 comments







E.g. If you wish to get the no. of posts a user have and the last ID of the post made, you might do something like:
SELECT COUNT(*), MAX(`id`) FROM `table` WHERE `user_id` = 1;
MySQL will throw a problem if there is no GROUP BY clause when the field added turns that query into:
SELECT COUNT(*), MAX(`id`), `Model`.`id` FROM `table` WHERE `user_id` = 1;
Will it be possible to include a toggle so we can optionally disable the auto adding?
function beforeSave() {
/**
* Checks table metadata for fields which allows NULL and set the value
* to NULL when they are empty
*
* TODO: probably make this a behavior?
*/
$tableInfo = $this->_tableInfo->get();
foreach ($tableInfo as $field) {
if ($field['null']) {
if (isset($this->data[$this->name][$field['name']]) && $this->data[$this->name][$field['name']] === '') {
$this->data[$this->name][$field['name']] = null;
}
}
}
return true;
}