CakePHP: One column -> one TRUE

↘锁芯ラ 提交于 2019-12-25 01:55:08

问题


Hope someone could help me with this:

I would like to have a column that will contain one and only one TRUE value. I want to set a value of TRUE (or '1') to a row and be assured that the remaining rows are FALSE (or '0').

How this could be achieved with CakePHP?


回答1:


You can't enforce this at the database level (well, you can if you use triggers) so you'll have to enforce it using Model::beforeSave()

Something along the lines of:

public function afterSave() {

    if ($this->data['Model']['field'] == 1) {
        // set all other records to false
        $this->updateAll(array('field'=>0));
    }

}

When the record is saved, it should be the only one with 'field' set to true.



来源:https://stackoverflow.com/questions/11259394/cakephp-one-column-one-true

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!