UpdateAll的魔力

Sad*_*san 10 cakephp cakephp-2.0

我在cakephp for和updateAll查询中编写了下面的代码

$this->loadModel('User');
$this->User->updateAll(array('stauts'=>'active'),array());
Run Code Online (Sandbox Code Playgroud)

上面代码的等效SQL查询就是这样生成的

UPDATE User SET status='active' WHERE 0 = 1;
Run Code Online (Sandbox Code Playgroud)

当我在cakephp中写下updateAll时,如下所示

$this->loadModel('User');
$this->User->updateAll(array('stauts'=>'active'));
Run Code Online (Sandbox Code Playgroud)

此代码的等效SQL查询是这样生成的

UPDATE User SET status='active';
Run Code Online (Sandbox Code Playgroud)

我不知道为什么会这样.

如果您不理解我的问题,请在评论中告诉我,我会在短期内解释.

AD7*_*six 16

这是一个安全问题

条件通常基于用户输入是动态的.考虑像这样的控制器动作:

function enableAll() {
    $conditions = array();

    ...

    if (whatever) {
        // Update only today's records
        $conditions['created > '] = $yesterday;
    }

    if ($this->Auth->user()) {
        // Update only my records
        $conditions['user_id'] = $this->Auth->user('id');
    }

    $this->Widget->updateAll(
        array('active' => 1),
        $conditions
    );
}
Run Code Online (Sandbox Code Playgroud)

逻辑条件可以是以下两种情况之一:

  • 匹配一些或没有记录的数组
  • 一个空数组

当它是一个空数组时,开发人员是否意味着更新所有记录,或者没有记录?

CakePHP无法确定,但如果通过,则一个空条件数组更可能是一个错误,其意图是什么都不更新.因此,为了保护开发人员不会意外更新所有内容,使用的条件与任何记录都不匹配(WHERE 0 = 1为假 - 它始终不匹配任何行).

这就是为什么这个:

// I definitely want to update the whole table
$model->updateAll($update);
Run Code Online (Sandbox Code Playgroud)

处理方式与此不同:

// mistake? maybe the conditions have been forgotten...
$model->updateAll($update, array()); 
Run Code Online (Sandbox Code Playgroud)