Jocky Doe Jocky Doe - 1 month ago 8
MySQL Question

Does Model::create make a db transaction

I came up to such code for one-to-one insert:

$anotherPet = \App\Pet::create($data);
$anotherUser = \App\User::create($data);
$anotherPet->user()->associate($anotherUser);

$anotherPet->save();


Does
create()
make a call to db or the transaction is made on
save()
?

3 vs 1 calls?

Appreciate your kind help.

Answer

Assuming you are using laravel, create does a transaction, if you want only one you can do create a new instance and fill it like this :

$anotherPet = new \App\Pet;
$anotherPet->fill($data);
$anotherUser = \App\User::create($data); // transaction is made here; mandatory to have an id for your association

$anotherPet->user()->associate($anotherUser); // no transaction
$anotherPet->save(); // transaction is made here

this way you have 2 queries instead of 3, i don't a way to make it in a single query without a foreign key constraint fail.