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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35042618/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 13:07:44  来源:igfitidea点击:

How can I maintain foreign keys when seeding database with Faker?

laravellaravel-5eloquentfaker

提问by Raihan Mahmud

Below is my model factory.

下面是我的模型工厂。

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

});

});

and This my database seeder class

这是我的数据库播种机类

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

But when I execute php artisan db:seed...it does not work..

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

What should be the workaround here..any help would be appreciated..

这里应该有什么解决方法..任何帮助将不胜感激..

回答by Ali Sherafat

you can get all ids using pluck(listsis depricated for laravel >= 5.2)

您可以使用pluck(lists对于 laravel >= 5.2 已弃用)获取所有 ID

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

and get a random id for FK column:

并为 FK 列获取一个随机 ID:

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

You may also attach relationships to models using Closure attributes in your factory definitions.

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

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

回答by Raihan Mahmud

I just found the workaround .. I replaced

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

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

with

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

and that solves the problem for now..

这解决了现在的问题..