*updated* Take care when using CakePHP Model->id, Model->del(), Model->find()

Fixed a bug recently in our code base that had happened intermittently enough for me to ignore until recently, when the problem occurred twice in a week. There was this habit of using the ‘id’ attribute of the corresponding model; e.g.

$options = array(); // method params
$this->Foo->id = 'bar';
$this->Foo->baz($options);

Now this is a fairly handy syntax, but unexpected results are produced when used in conjunction with find() and del(); e.g.

$options = array('contain' => array());
$this->Foo->id = 'bar';
$this->Foo->find('first', $options)); // BUG: not equivalent to setting the conditions key of $options to array('Foo.id' => 'bar'). SQL is NOT "select * from foo where id='bar';"

The above find() returns the first (cached?) row is returned, which is incorrect of course.

Now for del():

$this->Foo->id = 'bar';
$this->Foo->del(); // BUG: not equivalent to $this->Foo->del('bar'). SQL is NOT "delete from foo where id='bar';"

Unfortunately, results will vary, depending on the database engine. I suspect that sometimes the first cached(?) row — without any WHERE clause — is returned, and it happens to be ‘bar’, hence delete works correctly. For your reference, we use Oracle 11g Release 2.

HTH,
Wayne

Advertisements

2 thoughts on “*updated* Take care when using CakePHP Model->id, Model->del(), Model->find()

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s