Jocky Doe Jocky Doe - 2 months ago 12
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);


make a call to db or the transaction is made on

3 vs 1 calls?

Appreciate your kind help.


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;
$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.