0

我正在使用 laravel 工厂在我的数据库中生成一些假用户,但我不知道如何获取我当前正在生成的用户的用户 ID。我想获取当前用户的 id,以便可以对其进行哈希处理并将其放入 slug 中。

到目前为止,这是我的代码:

$factory->define(User::class, function (Faker $faker) {
$name = $faker->name;
$email = $faker->unique()->safeEmail;
$date_of_birth = $faker->date();

return [
    'name' => $name,
    'email' => $email,
    'email_verified_at' => now(),
    'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
    'remember_token' => Str::random(10),
    'date_of_birth' => $date_of_birth,
    'slug' => (\App\User::class)->id //This is the part that doesn't work,
];
});
4

3 回答 3

0

仅在将记录插入数据库后才分配 ID。所以没有办法在你的工厂里访问它。

假设您不仅需要 slug 作为测试/播种的一部分,最好的方法是挂钩模型的 created 事件:

class User extends Authenticatable
{
    protected static function boot() {
        parent::boot();

        static::created(function ($user) {
            $user->update(['slug' => $user->id]);
        });
    }
}
于 2019-08-23T11:47:19.710 回答
0

如果您的 users.id 是自动递增的,那么如果您使用我在评论中给出的问题的答案,通过使用静态变量并递增它,您可以获得相同的 ID。

$factory->define(App\AliasCommand::class, function (Faker\Generator $faker) {
    $name = $faker->name;
    $email = $faker->unique()->safeEmail;
    $date_of_birth = $faker->date();

    static $id = 1;

    return [
        'name' => $name,
        'email' => $email,
        'email_verified_at' => now(),
        'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
        'remember_token' => Str::random(10),
        'date_of_birth' => $date_of_birth,
        'slug' => $id++,
    ];
});

未经测试,但这是我前一段时间所做的。

于 2019-08-23T10:15:32.407 回答
0

另一种接近它的方法是在工厂外设置蛞蝓。

这意味着它slug需要可以为空。

移民:

$table->string('slug')->nullable();

工厂:

$factory->define(User::class, function (Faker $faker) {
$user = [
    'name' => $faker->name,
    'email' => $faker->unique()->safeEmail,
    'email_verified_at' => now(),
    'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
    'remember_token' => Str::random(10),
];

return $user;
});

播种机:

$users = factory(User::class, 5)->create();

foreach($users as $user) {
    $user->slug = $user->id;
    $user->save();
}

更新:

Laravel 提供工厂回调(参见文档

所以,你不需要在你的播种机中循环,只需链接afterCreating()方法:

$factory->define(App\User::class, function (Faker $faker) {
return [
    'name' => $faker->name,
    'email' => $faker->unique()->safeEmail,
    'email_verified_at' => now(),
    'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
    'remember_token' => Str::random(10),
];
})->afterCreating(\App\User::class, function (\App\User $user, Faker $faker) {
    $user->slug = $user->id;
    $user->save();
});
于 2019-08-23T11:36:33.463 回答