用户模型返回id=null
,而调试时我发现了这个问题的原因是在我的User
模型中,我用自定义变量覆盖了$primary_key
class User extends Authenticatable
{
use Notifiable;
// Set the primary key to the generated version instead of the regular ID
protected $primaryKey = 'user_code';
// Set the key type
protected $keyType = 'string';
// Diable the auto-increment option
public $incrementing = false;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'user_code',
'fname',
'mname',
'lname',
'email',
'dob',
'age',
'gender',
'insurance_number',
'ssn',
'avatar',
'is_active',
'userable_id',
'userable_type',
];
}
我有以下代码,这些代码生成一个使用user_code
id
$user = new User;
$user = $user->create([
'fname' => $request->fname,
'lname' => $request->lname,
'email' => $request->email,
]);
// Save the user in the DB
// Generate a usercode for the newely created user
$userCode = "ur" . date('y') . date('m') . $user->id;
用户迁移:
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('user_code')->unique()->nullable();
$table->string('fname')->default('tbd');
$table->string('mname')->default('tbd');
$table->string('lname')->default('tbd');
$table->string('email')->unique()->nullable();
$table->date('dob')->default('1000-01-01');
$table->integer('age')->default(0);
$table->string('gender')->default('tbd');
$table->integer('insurance_number')->default(0);
$table->integer('ssn')->default(0);
$table->string('avatar')->default('tbd');
$table->boolean('is_active')->default(false);
$table->string('userable_code')->default('tbd');
$table->string('userable_type')->default('tbd');
$table->timestamp('email_verified_at')->nullable();
$table->rememberToken();
$table->timestamps();
});
$user->id
返回null,为什么会发生这种情况?
答案 0 :(得分:2)
您已将$user
设置为新的模型实例:
$user = new User;
但是随后您尝试从该实例创建一个新用户,这将不起作用:
$user = $user->create([ ...
因为这行不通,所以您实际上并没有将任何内容保存到数据库,也不会获得ID。
问题的第二部分是(如@TimLewis在注释中指出的那样),您正在尝试创建和保存具有空白主键(user_code
)的模型。那是行不通的,因此您需要先确定ID是 ,然后再尝试保存ID。
// Remove this line:
// $user = new User;
// Find the current highest ID:
$last = User::max('id');
// Your new user will have this ID
$newID = $last->id + 1;
// And just use the normal way to create and save a model:
$user = User::create([
'userCode' => "ur" . date('y') . date('m') . $newID,
'fname' => $request->fname,
'lname' => $request->lname,
'email' => $request->email,
]);
答案 1 :(得分:0)
我可能不知道您要在这里实现什么,但是我只是假设这是一个非常特殊的用例。
尝试一下:
// Notice how we are using the User as a class, not instantiating it.
$user = User::create([
'fname' => $request->fname,
'lname' => $request->lname,
'email' => $request->email,
]);
// Save the user in the DB
// Generate a usercode for the newely created user
$userCode = "ur" . date('y') . date('m') . $user->id;
这假定数据库表中的id
列仍为INCREMENTS
和PRIMARY KEY