Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CakePHP: Always use clear() instead of create()?

there's a small, but very important difference, between calling clear() and create() within a loop:

let's assume the following code:

foreach ($posts as $post) {
  $this->Post->create();
  $this->Post->id = $post['Post']['id'];
  $this->Post->save(['column3' => 'foo', 'column4' => 'bar']);
}

When doing a create(): column 1, which might default to boolean false, is magically added to the updated-fields as well and can lead to a data loss (think of post with column1 = true).

When doing a clear() instead of create(): column 1, which is not mentioned in the save-statement is not touched at all.

So, is it always safe to rely on clear() in a foreach, where existing data is partially updated?

Second party of my question: Is it ALWAYS better to rely on clear()? (When looking at the code of clear(), you see, that it's only a convenience wrapper for create(false)). And the only difference in create() and create(false) is the initialization of the default values. I think, default values should better be set directly on database-level.

Btw: I just proposed a small doc change. Feel free to +1 this:

like image 674
Johannes N. Avatar asked Mar 19 '23 05:03

Johannes N.


1 Answers

So, is it always safe to rely on clear() in a foreach, where existing data is partially updated?

Yes.

Is it ALWAYS better to rely on clear()?

The only benefit of using create() when adding records is your form will be pre-populated with default values to be shown to user. So if you don't care about this you can always use clear().

like image 149
ADmad Avatar answered Mar 29 '23 10:03

ADmad