Skip to content

Instantly share code, notes, and snippets.

@zeelot
Created October 31, 2010 03:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zeelot/656057 to your computer and use it in GitHub Desktop.
Save zeelot/656057 to your computer and use it in GitHub Desktop.
saving related orm models with new ORM_Validation_Exception class
<?php
public function save(Validate $validate = NULL)
{
DB::query(NULL, 'START TRANSACTION')->execute();
try
{
parent::save($validate);
}
catch (ORM_Validation_Exception $e)
// No need to handle it until the end
// Any related model will simply merge its exception to $e
{}
// Let's try saving a related model if it has been altered
if (count($this->_related['item']->_changed) > 0)
{
$item = $this->_related['item'];
// Save the related item model
try
{
// Add the foreign key
$item->test_id = $this->id;
$item->save();
}
catch (ORM_validation_Exception $x)
{
// Create an exception if one was not thrown by the parent model saving
if ( ! isset($e))
{
$e = new ORM_Validation_Exception($this->_object_name, $this->validate());
}
// The merge method will namespace errors automatically based on the alias of the relationship
$e->merge('item', $x);
}
}
if (isset($e))
{
// If any of the models threw an exception, we need to rollback
DB::query(NULL, 'ROLLBACK')->execute();
throw $e;
}
else
{
DB::query(NULL, 'COMMIT')->execute();
}
// All went well
return $this;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment