簡體   English   中英

在Eloquent ORM中用不同的主鍵覆蓋用戶ID后,如何獲取用戶ID?

[英]How can I fetch user ID after overriding it with different primary key in Eloquent ORM?

用戶模型返回id=null ,而調試時我發現此問題的原因是在我的User模型中,我User自定義$primary_key覆蓋了$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',
    ];
}

我有以下代碼生成使用id的新user_code

$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,為什么會發生這種現象?

您已將$user設置為新的模型實例:

$user = new User;

但是,然后您嘗試從該實例創建一個新用戶,這將不起作用:

$user = $user->create([ ...

由於這行不通,因此您實際上並沒有將任何內容保存到數據庫,也不會獲得ID。

問題的第二部分是(如@TimLewis在注釋中指出的那樣),您正在嘗試創建和保存帶有空白主鍵( user_code )的模型。 那是行不通的,因此您需要先弄清楚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,
]);

我可能不知道您要在這里實現什么,但是我只是假設這是一個非常特殊的用例。

嘗試這個:

// 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列仍為INCREMENTSPRIMARY KEY

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM