Note that there are some explanatory texts on larger screens.

plurals
  1. POIs it safe to do query with Model while in Behavior's BeforeSave callback?
    primarykey
    data
    text
    <p>I don't see this documented anywhere, so I ask you, my dear Cake-eaters.</p> <p><strong>Inside</strong> a CakePHP's <strong><code>Behavior::BeforeSave(&amp;$Model)</code></strong> method, I read and write changes to <code>$Model-&gt;data</code> array. Before I am finished, I need to read some other records from the database. I am worried that, if I use <code>$Model-&gt;find()</code>, it will overwrite the current data within the model, which is about to be saved.</p> <p>Viewing the source code, the <a href="http://api20.cakephp.org/view_source/model#line-2476" rel="nofollow"><code>Model::find()</code></a> function clearly resets the <code>Model::$id</code> variable. This is the same variable I later use to check if a field is being updated.</p> <p>Here's an example:</p> <pre><code>&lt;?php class UniqueBehavior extends ModelBehavior { function beforeSave(&amp;$Model){ $value = $Model-&gt;data[$Model-&gt;alias]['unique_field']; $query = array('conditions' =&gt; array('unique_field' =&gt; $value)); if ($Model-&gt;find('first', $query){ // Does $Model::find() reset the internal $Model-&gt;data array? $Model-&gt;data[$Model-&gt;alias]['unique_field'] = "..." //... some other code here } //ALSO... if ($Model-&gt;exists()) // Returns true if a record with the currently set ID exists. $slug = $Model-&gt;field('slug'); // this should fetch the slug of the currently updated Model::id from the database // if I do find()'s, can I trust that the record I'm getting is the right one? } } ?&gt; </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload