在Laravel

时间:2018-05-31 07:19:07

标签: php laravel laravel-seeding

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

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();我该怎么做。

任何指导或即兴表示欢迎。

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:1)

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

但是,为了保存相关的模型,您首先需要创建一个假的,或者在您的情况下关联您已创建的角色。为此,您可以首先使用以下内容创建角色工厂:

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

正如你在角色工厂中看到的那样,我创建了一个随机角色,因为你说你已经手动创建了它们,所以如果你随机选择一个,那么你的公司将与你的一个角色随机相关! /强>

一旦你拥有:在DB,角色工厂中创建的角色,你可以使用工厂将随机角色与公司联系起来保存随机实例。

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;

    });