title: CakePHP Conundrum - Saving In A HasMany Relationship
body: <p>Okay, I'm tying myself up in knots here - I need clearer heads than mine to cut through to the centre of the problem!</p>
  
  <p>I have a model Livesession model which hasMany Sessiontracks.</p>
  
  <p>Someone edits the livesession, along with the sessiontracks information, which is submitted by the user in the same form.  </p>
  
  <p>At the moment, and this may be too elaborate by far, I'm doing this:</p>
  
  <pre><code>$temp = array();
  foreach ($this-&gt;data['Sessiontracks'] as $track) {
      if (!empty($track['name']) &amp;&amp; !empty($track['starts_at'])) {
          $temp[] = $track;
      }
  }
  $this-&gt;data['Sessiontracks'] = $temp;
  
  $this-&gt;Livesession-&gt;Sessiontracks-&gt;deleteAll(
    array('livesession_id'=&gt;$this-&gt;data['Livesession']['id'])
  );
  if ($fileok &amp;&amp; this-&gt;Livesession-&gt;saveAll($this-&gt;data)) {
      // success!
  } else { // failure! }
  </code></pre>
  
  <p>This works fine, as far as it goes, for grabbing the sessiontracks info from the form, and replacing old sessiontracks info with new info every time the form is edited.  <strong>If</strong> the save is successful.  If the save fails, for instance if the editor tries to blank a compulsory field, then all their sessiontracks info is deleted from the database, and not replaced with anything.  </p>
  
  <p>I can't delete the sessiontracks info after I've saved it; and if I don't delete it at all, I end up with duplicate and/or erroneous information in the sessiontracks table.  But I really don't want a user to enter a huge bunch of track information and run the risk of losing it by attempting a bad edit.</p>
  
  <p>Perhaps I could retain the old sessiontracks info and save it back into  the table after the deleteAll if the saveAll fails?  I'm definitely feeling, though, that I've probably gone down completely the wrong route with this, and don't want to dig myself in any deeper.</p>
  
  <p>What's the best way of ensuring that I keep Livesession's associated data, even in the event of a save failure?</p>