在ModelFactory Laravel中为多个自定义行/条目设定种子

时间:2017-09-26 07:16:48

标签: php laravel eloquent

如何在Laravel中使用ModelFactory播种多行?

ModelFactory.php内我有以下代码:

$factory->define(App\User::class, function (Faker $faker) {
    static $password;

    return [
        'name' => 'Admin',
        'Description' => 'Administrators have full access to everything.'
    ];
});

如何在不使用原始表达式的情况下添加以下数组?

[
    'name' => 'Admin',
    'description' => 'Administrators have full access to everything.',
],
[
    'name' => 'User',
    'description' => 'User have normal access.',
],

由于

3 个答案:

答案 0 :(得分:0)

假设您要在数据库中添加100个用户。

UserFactory.php中创建database/factories

<?php

use Faker\Generator as Faker;

$factory->define(App\User::class, function (Faker $faker) {

    return [
        'name' => 'Admin',
        'Description' => 'Administrators have full access to everything.'
    ];
});

然后,在database/seeds/DatabaseSeeder.php

<?php

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        factory(App\User::class, 100)->create();
    }
}

您可以找到更多详情about seeding in the Laravel official documentation

答案 1 :(得分:0)

如果您希望有一两列具有自定义数据,则可以在创建条目后使用each函数。

$names = ['admin', 'user', 'author', 'subscriber'];

factory(App\User::class, 100)->create()->each(function () use ($names) {
     $user->name = $names[array_rand($names)];
     $user->save();
});

*注意:在每个函数中使用自己的逻辑来馈送自定义数据。

答案 2 :(得分:0)

比 Raghavendra 的提议更简洁的方法(每个名称创建一个条目):

$names = ['admin', 'user', 'author', 'subscriber'];

collect($names)->each(function($name) {
    App\Models\User::factory()->create($name);
});