Why not use factories where it's built right in? https://laravel.com/docs/9.x/database-testing#factory-relationships
Jul 20, 2022
6
Level 8
How to seed the relationship table?
Currently I have a loop to create records on both table1 and table2. But I need to get the last inserted ids from the tables in order to insert it to the relationship table. But how can I get the two id's? This is the current code:
for ($i = 0; $i < 100; $i++) {
$table1_name = fake()->name(100);
DB::table('table1')->insert([
'name' => $table1_name
]);
$table2_name = fake()->name(100);
DB::table('table2')->insert([
'name' => $table2_name
]);
}
So I need to then insert the created id from table1 and table2 on the same iteration:
// inside the for loop, under table2 insert:
DB::table('table1_table2')->insert([
'table1_id' => // last inserted table1 id,
'table2_id' => // last inserted table2 id
]);
How can I do that?
Ty!
Level 102
@Ligonsker ah sorry use insertGetId() instead of insert()
1 like
Please or to participate in this conversation.