Laravel-种子关系 [英] Laravel - Seeding Relationships

查看:105
本文介绍了Laravel-种子关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Laravel中,数据库播种通常是通过Model工厂完成的.因此,您可以使用Faker数据为模型定义一个蓝图,并说出需要多少个实例:

In Laravel, database seeding is generally accomplished through Model factories. So you define a blueprint for your Model using Faker data, and say how many instances you need:

$factory->define(App\User::class, function (Faker\Generator $faker) {
    return [
        'name' => $faker->name,
        'email' => $faker->email,
        'password' => bcrypt(str_random(10)),
        'remember_token' => str_random(10),
    ];
});

$user = factory(App\User::class, 50)->create();

但是,可以说您的User模型与许多其他模型具有hasMany关系,例如Post模型:

However, lets say your User model has a hasMany relationship with many other Models, like a Post model for example:

Post:
   id
   name
   body
   user_id

因此,在这种情况下,您想为已发布在Users表中的 实际 用户作为Posts表的种子.似乎没有对此进行明确讨论,但是我确实在Laravel文档中找到了以下内容:

So in this situation, you want to seed your Posts table with actual users that were seeded in your Users table. This doesn't seem to be explicitly discussed, but I did find the following in the Laravel docs:

$users = factory(App\User::class, 3)
    ->create()
    ->each(function($u) {
         $u->posts()->save(factory(App\Post::class)->make());
    });

因此,在您的用户工厂中,您为创建的每个用户创建X个帖子.但是,在大型应用程序中,可能有50-75个模型与用户模型共享关系,您的用户播种机实际上最终将为所有数据库提供所有关系.

So in your User factory, you create X number of Posts for each User you create. However, in a large application where maybe 50 - 75 Models share relationships with the User Model, your User Seeder would essentially end up seeding the entire database with all it's relationships.

我的问题是:这是处理此问题的最佳方法吗?我唯一想到的另一件事是,先播种用户(不播种任何关系),然后在播种其他模型时根据需要从数据库中抽取随机用户.但是,在需要唯一的情况下,您必须跟踪使用过哪些用户.而且,这似乎会在播种过程中增加大量额外的查询.

My question is: Is this the best way to handle this? The only other thing I can think of is to Seed the Users first (without seeding any relations), and then pull random Users from the DB as needed while you are seeding other Models. However, in cases where they need to be unique, you'd have to keep track of which Users had been used. Also, it seems this would add a lot of extra query-bulk to the seeding process.

推荐答案

您也可以使用saveMany.例如:

You can use saveMany as well. For example:

factory(User::class, 10)->create()->each(function ($user) {
    $user->posts()->saveMany(factory(Posts::class, 5)->make());
});

这篇关于Laravel-种子关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆