英文:
Laravel one to many table seed is not seeded as expected
问题
我有一个类似这样的关系表ERD。我在Laravel中使用Eloquent数据库关系来管理外键。
它运行正常,但是添加的数据跳过了一行。
这是我如何填充数据库的方式。
public function run(): void
{
User::factory()
->has(FavPlant::factory(),'fav_Plant')
->count(5)
->create();
Plants::factory()
->has(FavPlant::factory(),'fav_Plant')
->count(5)
->create();
}
如何使关系表同时具有user_id
和plants_id
?
英文:
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?
答案1
得分: 1
你似乎在用户和植物之间通过 FavPlant 枢纽表建立了多对多的关系。你可以像下面这样同时设置 user_id
和 plant_id
。
public function run(): void
{
$users = User::factory()
->count(5)
->create();
$plants = Plant::factory()
->count(5)
->create();
// 使用循环为 FavPlant 枢纽表建立关系
foreach ($users as $user) {
foreach ($plants as $plant) {
FavPlant::factory([
'user_id' => $user->id,
'plant_id' => $plant->id,
])->create();
}
}
}
英文:
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();
}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论