Toggling a database flag field in CakePHP

2014-06-07

Sometimes we have to make a data model that involves various flags to indicate different statuses for an object. For example, a Post can have attributes like active or comments_allowed which can have either the value 0 (off) or 1 (on). Often we wish to toggle these values; how do this in an elegant fashion? (scroll to the bottom for the one-liner)

We could grab the value:


$post = $this->Post->read(null, $id);
if($post['Post']['active'] == 1) {
    $post['Post']['active'] = 0;
} else {
    $post['Post']['active'] = 1;
}
$this->Post->save($post);

More elegant would be to use a ternary operator like so:


$post = $this->Post->read(null, $id);
$post['Post']['active'] = $post['Post']['active'] == 1 ? 0 : 1;
$this->Post->save($post);

But in principle, we do not even need to grab the old value from the database to toggle the value:


$post = $this->Post->query("UPDATE `posts` SET `active`= IF(`active`=1, 0, 1) WHERE `id`='$id'");

We can even get rid of the if statement:


$post = $this->Post->query("UPDATE `posts` SET `active`= 1 - `active` WHERE `id`='$id'");

And there you go, a simple one-liner.

If you have questions or comments, feel free to drop a line! Like what you read? Share this page with your friends and colleagues.

Comments

Question:
What is the answer to Ten + Five?
Please answer with a whole number, i.e. 2, 3, 5, 8,...