在制作相同型号的工厂时如何使用型号 ID?
How do I use a models id while making a factory of the same model?
我想做的是在工厂中获取用户 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' => 'yIXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
'remember_token' => Str::random(10),
];
});
$this->id
in 'hashed_id' => Hashids::encode($this->id)
假设是指 User::class
错误
ErrorException: Undefined property: 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);
});
}
我想做的是在工厂中获取用户 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' => 'yIXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
'remember_token' => Str::random(10),
];
});
$this->id
in 'hashed_id' => Hashids::encode($this->id)
假设是指 User::class
错误
ErrorException: Undefined property: 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);
});
}