Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Magic of UpdateAll

I wrote the code below in cakephp for and updateAll query like

$this->loadModel('User');
$this->User->updateAll(array('stauts'=>'active'),array());

The above code's equivalent SQL query is generated like this

UPDATE User SET status='active' WHERE 0 = 1;

When I write updateAll in cakephp like below

$this->loadModel('User');
$this->User->updateAll(array('stauts'=>'active'));

This code's equivalent SQL query is generated like this

UPDATE User SET status='active';

I don't know why this happens.

If you do not understand my question let me know in comments, I'll explain in shortly.

like image 396
Sadikhasan Avatar asked Jun 17 '14 08:06

Sadikhasan


1 Answers

It's a safety catch

Conditions are often dynamic based on user input. Consider a controller action like so:

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
    );
}

Logically conditions can be one of two things:

  • An array matching some or no records
  • An empty array

When it's an empty array, did the developer mean to update all records, or no records?

CakePHP can't know for sure, but if passed, an empty conditions array is more likely to be an error where the intention was to update nothing. Therefore to protect developers from accidentally updating everything, a condition is used which won't match any records (WHERE 0 = 1 is false - it will match no rows, always.).

That's why this:

// I definitely want to update the whole table
$model->updateAll($update);

is treated differently than this:

// mistake? maybe the conditions have been forgotten...
$model->updateAll($update, array()); 
like image 138
AD7six Avatar answered Sep 20 '22 01:09

AD7six