Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

spacedog4's avatar

Insert records from different tables with one query

I want to use the bennefit of factories, I'm improving the performance of my tests, today I have more the 400 tests, I need to refresh the database before each test, but also need 3 records from 3 different tables on each test (not all, but most)

I want to transform this code

$this->empresa = factory(Empresa::class)->create([
    'codigoempresa' => 1
]);
$pessoa = factory(Pessoas::class)->create([
    'codigoempresa' => 1,
    'codigopes' => 1
]);

$this->apiUser = factory(ApiUser::class)->create([
    'codigoempresa' => $this->empresa->codigoempresa,
    'codigopes'     => $pessoa->codigopes,
    'api_token'     => $this->token
]);

in just one query for performance improvement, I was thinking in DB::raw() but I don't know how to integrate that with factories

0 likes
4 replies
tykus's avatar
tykus
Best Answer
Level 104

You cannot insert to multiple tables using a single query.

spacedog4's avatar

I mean,

" Insert ...; insert ...; insert ...; "

would be better than calling the builder 3 times

tykus's avatar

Why? The factory gives you back the instance (based on the data used to build the Model), whereas a raw DB::insert would require further queries to refetch the records.

1 like
spacedog4's avatar

I also realized that if I used insert I would need to make another query to get the instance

Please or to participate in this conversation.