如何在制作相同模型的工厂时使用模型 ID?

  • 本文关键字:模型 工厂 ID laravel factory
  • 更新时间 :
  • 英文 :


我想做的是在工厂中获取用户ID,以便我可以存储它的哈希版本:

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

'hashed_id' => Hashids::encode($this->id)中的$this->id是指User::class

错误

错误异常:未定义的属性:Illuminate\Database\Eloquent\Factory::$id

您应该创建一个观察者来跟踪每个数据库记录的创建。

这将允许您代理创建和修改数据。

请参阅:https://laravel.com/docs/5.8/eloquent#observers

或者,可以直接向模型上的模型事件添加挂钩。

protected static function boot()
{
parent::boot();
static::creating(function ($user) {
$user->hashed_id = Hashids::encode($user->id);
});
}

最新更新