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: