-
Notifications
You must be signed in to change notification settings - Fork 4
Saving and Deleting
Saving and deleting objects in Corma is very easy. Create your object via create(), call setters to set data, and call the save() or saveAll() methods on the ObjectMapper to insert or update your objects, call delete() or deleteAll() to delete objects. Unlike Doctrine ORM, everything is executed immediately, there is no flush method.
$object = $orm->create(YourDataObject::class);
//Call setters...
$orm->save($object); //insert
//Call more setters...
$orm->save($object); //update
//Call more setters on $object...
$objects = [$object];
$newObject = $orm->create(YourDataObject::class);
//call setters on $newObject..
$objects[] = $newObject;
$orm->saveAll($objects); //1 update 1 insert
$orm->deleteAll($objects);
By default, Corma's save() and saveAll() repository methods do not save any associations. To save related entities, extend saveRelationships on your object's repository, and return a closure using RelationshipManager that will be used in save and saveAll to efficiently and safely persist child objects to the database.
class YourDataObjectRepository extends ObjectRepository
{
protected function saveRelationships(): array|\Closure|null
{
return function(array $objects) {
// Save all relationships specified in YourDataObject
$this->objectMapper->getRelationshipManager()->saveAll($objects);
});
}
}
class YourDataObjectRepository extends ObjectRepository
{
protected function saveRelationships(): array|\Closure|null
{
// save only the otherObject relationship by default
return ['otherObject'];
}
}
The behavior specified in your repository can be overridden when calling save or saveAll.
$object = $orm->create(YourDataObject::class);
$object->setOtherObject($otherObject);
//Save all relationships
$orm->save($object, '*');
//Only save otherObject, and manyObject changes
$orm->save($object, 'otherObject', 'manyObjects');
//Or don't save any relationships
$orm->save($object, null);
Outside of your repositories you can easily wrap code in a transaction using a unit of work.
class YourClass
{
public function yourFunction()
{
//Create / retrieve some data objects...
//functional style
$this->corma->unitOfWork()->executeTransaction(function() use($object1, $object2) {
$this->corma->save($object1);
$object2->setObjectId($object1->getId());
$this->corma->save($object2);
});
//doctrine style
$unitOfWork = $this->corma->unitOfWork();
$unitOfWork->save($object1);
$unitOfWork->save($object2);
$unitOfWork->delete($object3);
$unitOfWork->flush(); //actually does the saves and delete in a transaction
}
}