使用Faker为数据库播种时如何维护外键?

时间:2016-01-27 16:20:47

标签: laravel laravel-5 eloquent faker

以下是我的模型工厂。

$factory->define(App\Business::class, function (Faker\Generator $faker){
return [
'name' => $faker->bs,
'slug' => $faker->slug,
'address' => $faker->streetAddress,
'phone_no' => $faker->phoneNumber,
'mobile_no' => $faker->phoneNumber,
'email' => $faker->companyEmail,
'website' => $faker->domainName,
'latitude' => $faker->latitude,
'longitude' => $faker->longitude,
'location' => $faker->city,
'business_days_from' => $faker->dayOfWeek,
'business_days_to' => $faker->dayOfWeek,
'description' => $faker->text,
'user_id' => $faker->factory(App\User::class),
];

});

和我的数据库播种器类

class DatabaseSeeder extends Seeder
{
    public function run()
    {
        factory(App\Business::class, 300)->create();
    }
}

但是当我执行 php artisan db:seed 时......它不起作用..

这里的解决方法应该是什么......任何帮助都将受到赞赏..

2 个答案:

答案 0 :(得分:2)

您可以使用pluck获取所有ID(lists已针对laravel> = 5.2进行了展示)

$userIds = User::all()->pluck('id')->toArray();

获取FK列的随机ID:

'user_id' => $faker->randomElement($userIds) 

您还可以使用工厂定义中的Closure属性将关系附加到模型。

    'title' => $faker->title,
    'content' => $faker->paragraph,
    'user_id' => function () {
        return factory(App\User::class)->create()->id;
    }

答案 1 :(得分:0)

我刚刚找到了解决方法..我替换了

'user_id' => $faker->factory(App\User::class),

'user_id' => $faker->randomElement(User::lists('id')->toArray()),

现在解决了这个问题..