dongye9820 2018-05-31 07:19
浏览 128
已采纳

种子数据与Laravel的关系

I'm trying to seed my Laravel 5.6 application through faker factory, I went through the link and little bit confused, As I have some basic static data, like for example I've a company model:

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

And a relational role model:

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'
    ];

}

and respective database, I'm following the laravel convention, Now I want to seed the data:

I've particular set of roles which I'm seed in manually,

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],
        ]);

    }
}

For company I want to create factory so I did:

$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')
    ];
});

And in company seed I'm having:

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

Help me at place $company->roles()->save(); What should I do over here.

Any guidance or improvisation welcome.

  • 写回答

2条回答 默认 最新

  • douxian4888 2018-05-31 07:31
    关注

    You can query which roles you want to assign to the companies and related them to the created records like this:

    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
                ]);
            });
        }
    }
    

    You can check the doc for relating records https://laravel.com/docs/5.6/eloquent-relationships#inserting-and-updating-related-models

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号