【发布时间】:2021-06-30 11:32:57
【问题描述】:
我在用户表中有一些字段:
id firstName lastName userName
这里我需要自动生成并保存一个用户名,用户将只提供名字和姓氏。我尝试过类似的方法,但不确定这段代码。
User.php
class User extends Authenticatable{
...
protected $appends = ['firstName', 'lastName', 'userName'];
protected $attributes = ['userName' => 'default'];
public static function boot()
{
parent::boot(); // TODO: Change the autogenerated stub
self::creating(function ($model) {
$randNum = rand(10, 99);
$userName = $model['firstName'] . $model['lastName'] . $randNum;
$model->userName = $userName;
});
}
}
所以每当我尝试迁移和播种时,它都会显示
“用户名”字段没有默认值
播种机是
public function run()
{
DB::table('users')->insert([
'firstName' => 'Osman',
'sureName' => 'Rafi',
'email' => 'rafi.ogchy@gmail.com',
'password' => Hash::make('password'),
]);
}
【问题讨论】: