Recently I have been trying to seed my database using Laravel seeding through Model Factories and Faker.

对于简单的模式,让它工作起来很容易:).然而,在使用复杂的数据库模式时,我遇到了几个问题,涉及foreign keys and table relationships个:

  • 一对一
  • 一对多
  • Many to Many

...如链接中所述:

在本主题中,official documentation建议按如下方式运行数据库种子:

public function run()
{
    factory(App\User::class, 50)->create()->each(function ($u) {
        $u->posts()->save(factory(App\Post::class)->make());
    });
}

... but there is one problem with this solution: when working with many DB tables and running many seeds (with many relations between them), it is common to create many unnecessary models using this methodology. For instance, if we had run the PostsTableSeeder.php before the one of the above example, all those posts would not have been linked to users, and would never be used in tests and development...

So searching for a way to handle this situation, I have come up to a functional solution that works for me and avoids the unnecessary creation of those 'orphan' models...

And I wanted to share it with everyone, so it is just explained in the answer :).

推荐答案

下面是我的解决方案:

该示例处理以下内容:

  • Users & Profiles (for illustrating One to One relationships)
  • Users & Posts (for illustrating One to Many relationships)

    // ONE TO ONE relationship (with Users already created)
    $factory->define(App\Profile::class, function (Faker\Generator $faker) {
        return [
            'user_id' => $faker->unique()->numberBetween(1, App\User::count()),
            // Rest of attributes...
        ];
    });
    
    // ONE TO MANY relationship (with Users already created)
    $factory->define(App\Posts::class, function (Faker\Generator $faker) {
        $users = App\User::pluck('id')->toArray();
        return [
            'user_id' => $faker->randomElement($users),
            // Rest of attributes...
        ];
    });
    

Laravel相关问答推荐

用Laravel Filament创建变形组件

在 Laravel 中排序的集合在 Vue 中突然不再排序

如何仅将日期列解析为月和日?

使用 fetch api 时 Laravel 控制器不存在错误

如何在 laravel 中为另一个用户 session()->forget('cart')?

前端和管理员分开时未加载laravel 9中间件

Laravel PHP 框架的新手. /以外的路由不起作用

从 laravel/blade 中的数组创建逗号分隔列表?

Laravel Electron邮件验证模板位置

Laravel 干预图像 GD 库扩展

Eloquent 的 Model::query() 是什么意思?

如何在包中安排 Artisan 命令?

如何在 Laravel 5.1 中改变环境?

Laravel 5 环境配置数组?

laravel:Eloquent的例子将数据插入数据库

Laravel 检测手机/平板电脑并加载正确的视图

Laravel php artisan 产生错误

Laravel 仓库

如何在 Laravel 中 Refresh刷新用户对象?

错误:找不到模块 'webpack/lib/rules/DescriptionDataMatcherRulePlugin' 需要堆栈: