Laravel一对多表种子未按预期种植。

huangapple go评论72阅读模式
英文:

Laravel one to many table seed is not seeded as expected

问题

我有一个类似这样的关系表ERD。我在Laravel中使用Eloquent数据库关系来管理外键。

它运行正常,但是添加的数据跳过了一行。

Laravel一对多表种子未按预期种植。

这是我如何填充数据库的方式。

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_idplants_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.

Laravel一对多表种子未按预期种植。

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_idplant_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();
        }
    }
}

huangapple
  • 本文由 发表于 2023年8月5日 07:23:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/76839576.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定