我有一个包含两个栏目,品牌和商店的数据库。每个品牌都可以欠几家商店,我想通过Fakers使用Laravel为我的数据库播种。
因此,在设置模型中的迁移和关系后
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Brand extends Model
{
/**
* Get the shops for the brand.
*/
public function shops()
{
return $this->hasMany('App\Shop','sh_brand_id');
}
}
和
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Shop extends Model
{
public function user() {
return $this->belongsTo('App\Brand','sh_brand_id');
}
}
我想使用Factory来为数据库设定种子。
<?php
use Faker\Generator as Faker;
$factory->define(App\Shop::class, function (Faker $faker) {
return [
'name' => $faker->company,
'address' => $faker->address,
];
});
和
use Faker\Generator as Faker;
$factory->define(App\Brand::class, function (Faker $faker) {
return [
'name' => $faker->company,
'logo_url' => $faker->imageUrl(640, 480),
'website' => $faker->url,
'description' => $faker->text(500),
'telephone_number' =>'31'. $faker->randomNumber(8),
'principal_address' => $faker->address,
'email' => $faker->unique()->safeEmail,
];
});
最后我需要使用那些工厂为数据库播种。网站上有文档和许多示例,但我发现每个解决方案都让我为每个品牌只生成一个商店,我想为每个品牌生成许多商店。
这样做的最佳方式是什么?
答案 0 :(得分:3)
直接将其放在您的工厂中。我使用辅助方法getInstanceOf
来选择另一个模型的随机实例。
use Faker\Generator as Faker;
use App\Brand;
use App\Shop;
function getInstanceOf($class, $returnIdOnly = true) {
$instance = $class::inRandomOrder()->first() ?? factory($class)->create();
return $returnIdOnly ? $instance->id : $instance;
}
$factory->define(Shop::class, function (Faker $faker) {
return [
'name' => $faker->company,
'address' => $faker->address,
'sh_brand_id' => getInstanceOf(Brand::class)
];
});
然后在播种时
factory(App\Brand::class, 10);
factory(App\Shop::class, 50);
答案 1 :(得分:1)
我发现这个解决方法对我有用:
<?php
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder {
/**
* Run the database seeds.
*
* @return void
*/
public function run() {
factory(App\Brand::class, 50)->create()
->each(
function ($br) {
factory(App\Shop::class, 10)->create()
->each(
function($sh) use (&$br) {
$br->shops()->save($sh)->make();
}
);
}
);
}
}