Hi, I'm trying to create multiple records across multiple models.
I have to following code, and setup to correct relations in the initialize method of the models:
$user = new \User();
$user->assign($this->request->getPut());
$user->status = 'active';
$location = new \Location();
$location->assign($this->request->getPut());
$location->type = 'logistic';
$location->User = $user;
$company = new \Company();
$company->assign($this->request->getPut());
$company->Location = $location;
if(!$company->create()) {
var_dump($company->getMessages());
return false;
}
The User model has a validation method to check unique email addresses:
public function validation() {
$this->validate(new Validator\Uniqueness([
'field' => ['email'],
]));
return $this->validationHasFailed() != true;
}
When I save the first time, it works fine, and the parent record and all related records are created.
The second time however, I get the var_dump
with Value of fields: email are already present in another record
, this is as expected.
What isn't expected is that the rows in both the company and location tables are still created, even when the user record fails.
The documentation clearly states:
Saving the album and the artist at the same time implicitly makes use of a transaction so if anything goes wrong with saving the related records, the parent will not be saved either. Messages are passed back to the user for information regarding any errors.
Is there anything I'm missing here?
Gr. Tim