开发者

CakePHP Conundrum - Saving In A HasMany Relationship

Okay, I'm tying myself up in knots here - I need clearer heads than mine to cut through to the centre of the problem!

I have a model 开发者_Go百科Livesession model which hasMany Sessiontracks.

Someone edits the livesession, along with the sessiontracks information, which is submitted by the user in the same form.

At the moment, and this may be too elaborate by far, I'm doing this:

$temp = array();
foreach ($this->data['Sessiontracks'] as $track) {
    if (!empty($track['name']) && !empty($track['starts_at'])) {
        $temp[] = $track;
    }
}
$this->data['Sessiontracks'] = $temp;

$this->Livesession->Sessiontracks->deleteAll(
  array('livesession_id'=>$this->data['Livesession']['id'])
);
if ($fileok && this->Livesession->saveAll($this->data)) {
    // success!
} else { // failure! }

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. If 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.

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.

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.

What's the best way of ensuring that I keep Livesession's associated data, even in the event of a save failure?


just $ids = find('list',array('conditions'=>array(..))) before you saveAll, then deleteAll(array('conditions'=>array('Model.id'=>$ids))) after the save is successful.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜