So I have a relationship table like this ERD. I’m using eloquent database relationship in laravel to manage the foreign key.
It worked, but the data added is skipping one row.
This is how I seed the database.
public function run(): void
{
User::factory()
->has(FavPlant::factory(),'fav_Plant')
->count(5)
->create();
Plants::factory()
->has(FavPlant::factory(),'fav_Plant')
->count(5)
->create();
}
How do I make the relation table have both user_id and plants_id simultaneously?
>Solution :
You seem to have a many-to-many relationship between users and plants through the FavPlant pivot table. You can set both user_id and plant_id at the same time as below.
public function run(): void
{
$users = User::factory()
->count(5)
->create();
$plants = Plants::factory()
->count(5)
->create();
// Seed FavPlant pivot table with relationships
foreach ($users as $user) {
foreach ($plants as $plant) {
FavPlant::factory([
'user_id' => $user->id,
'plants_id' => $plant->id,
])->create();
}
}
}
