具有 Laravel 关系的种子数据

Seed data with relationship in Laravel

我试图通过 faker 工厂为我的 Laravel 5.6 应用程序播种,我经历了 link 并且有点困惑,因为我有一些基本的静态数据,例如我已经公司模特:

class Company extends Model {

    use SoftDeletes, HasDataSearchTable, HasSlug;

    protected $fillable = [
        'name', 'code_link', 'slug', 'establishment', 'parent_id', 'website', 'updates', 'user_id', 'tracked', 'verified', 'active', 'premium', 'status'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'created_at','updated_at','deleted_at'
    ];

    public function roles()
    {
        return $this->belongsToMany('Noetic\Plugins\Conxn\Models\Variables\Company\Role', 'company_role_relation', 'company_id', 'role_id')->withTimestamps();
    }
}

和关系角色模型:

class Role extends Model
{
    use SoftDeletes  , HasDataSearchTable;

    protected $table='company_role';

    protected $fillable = [
        'name', 'parent_id'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'created_at','updated_at','deleted_at'
    ];

}

和相应的数据库,我遵循 laravel 约定,现在我想播种数据:

我有一组特定的角色,我是手动播种的,

class CompanyRoleSeed extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        DB::table('company_role')->insert([
            ['name' => 'Contractor', 'parent_id' => null],
            ['name' => 'Consultant', 'parent_id' => null],
            ['name' => 'Manufacturer', 'parent_id' => null],
            ['name' => 'Miscellaneous', 'parent_id' => null],
            ['name' => 'Owner', 'parent_id' => null],
            ['name' => 'Supplier', 'parent_id' => null],
        ]);

    }
}

对于我想创建工厂的公司,我这样做了:

$factory->define(Company::class, function (Faker $faker) {


    return [
        'name' => $faker->company,
        'code_link' => rand(5, 10),
        'slug' => str_slug($faker->company),
        'about' => $faker->paragraphs(),
        'establishment' => $faker->randomElement('2015', '2016', '2017', '2018'),
        'parent_id' => $faker->randomElement(null, '1', '2', '3'),
        'website' => $faker->url,
        'user_id' => $faker->randomElement('1', '2', '3', '4', '5'),
        'updates' => $faker->paragraphs(),
        'tracked' => $faker->boolean,
        'verified' => $faker->boolean,
        'active' => $faker->boolean,
        'premium' => $faker->boolean,
        'status' => $faker->randomElement('saved', 'draft')
    ];
});

在公司种子中我有:

class CompanySeed extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        factory(Company::class, 10)->create()->each(function ($company) {
            $company->roles()->save(); // Don't now how to execute here
        });
    }
}

到地方帮我$company->roles()->save();我这边怎么办

欢迎任何指导或即兴发挥。

您可以查询要分配给公司的角色并将它们与创建的记录相关联,如下所示:

class CompanySeed extends Seeder
{
    public function run()
    {
        $contractorRole = Role::whereName('Contractor')->firstOrFail();
        $ownerRole = Role::whereName('Owner')->firstOrFail();

        factory(Company::class, 10)->create()->each(function ($company) use ($contractorRole, $ownerRole) {
            $company->roles()->attach([
                $contractorRole->id,
                $ownerRole->id
            ]);
        });
    }
}

相关记录可以查看文档https://laravel.com/docs/5.6/eloquent-relationships#inserting-and-updating-related-models

在回答您的问题之前,您应该知道 Laravel 的文档解释了如何做 this

但是为了保存相关模型,您首先需要创建一个假模型,或者在您的情况下关联一个您已经创建的角色。为了做到这一点,您可以首先使用类似这样的东西创建一个角色工厂:

$factory->define(App\Role::class, function (Faker $faker) {
    $randomRoleAlreadyCreated = \App\Role::all()->random();
    return [
        'name' => $randomRoleAlreadyCreated->name, 
        'parent_id' => $randomRoleAlreadyCreated->parent_id
    ];
});

正如您在我创建的角色工厂中看到的那样,我随机抽取了一个角色,因为您说您已经手动创建了它们,因此如果您随机选择一个角色,那么您的公司将与您的其中一个角色相关联随机!

一旦您拥有:在数据库中创建的角色,角色工厂,您可以将随机角色与使用工厂的公司相关联,以保存随机实例。

factory(Company::class, 10)->create()->each(function ($company) {
        $company->roles()->save(factory(App\Role::class)->make()); // Don't now how to do here
    });

更新 如果您想为每个公司保存多个角色,您可以这样做:

factory(Company::class, 10)->create()->each(function ($company) {
        // Instead of 4 you could also create a random number 
        // using $numberOfRolesToAttach = rand($min,$max)
        for($i = 1; $i <= 4; $i++) :
            $company->roles()->save(factory(App\Role::class)->make());
        endfor;

    });