【发布时间】:2018-11-10 03:23:47
【问题描述】:
我正在尝试通过faker factory 为我的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();的地方帮帮我,我该怎么办。
欢迎任何指导或即兴创作。
【问题讨论】:
标签: php laravel laravel-seeding