Laravel model::create() 不返回主键

我有一个以下身份验证表:


<?php


use Illuminate\Database\Migrations\Migration;

use Illuminate\Database\Schema\Blueprint;

use Illuminate\Support\Facades\DB;

use Illuminate\Support\Facades\Schema;


class CreateAuthTable extends Migration

{

    /**

     * Run the migrations.

     *

     * @return void

     */

    public function up()

    {

        Schema::create('auth', function (Blueprint $table) {

            $table->uuid('id')->primary();

            $table->string('email', 255)->index()->unique();

            $table->string('password', 96);

            $table->timestamps();

        });

        DB::statement('ALTER TABLE auth ALTER COLUMN id SET DEFAULT uuid_generate_v4();');

    }


    /**

     * Reverse the migrations.

     *

     * @return void

     */

    public function down()

    {

        Schema::dropIfExists('auth');

    }

}


这是模型:


<?php


namespace App\Models;


use Illuminate\Database\Eloquent\Model;

use Illuminate\Foundation\Auth\User as Authenticable;

use Illuminate\Support\Facades\Hash;

use Laravel\Passport\HasApiTokens;


class User extends Authenticable

{

    use HasApiTokens;


    protected $table = "auth";

    protected $fillable = ["email", "password"];

    public $incrementing = false;

    protected $keyType = 'string';

    protected $casts = [

        'id' => 'string'

    ];


    private $hashOptions = [

        'memory' => 1024,

        'time' => 2,

        'threads' => 1

    ];


    public function setPasswordAttribute($value)

    {

        $this->attributes['password'] = Hash::make($value, $this->hashOptions);

    }

}


梦里花落0921
浏览 81回答 1
1回答

慕工程0101907

只需确保强制转换为字符串且主键名称正确namespace App;use Illuminate\Database\Eloquent\Model;class User extends Model{&nbsp; protected $casts = [&nbsp; &nbsp; 'id' => 'string'&nbsp; ];&nbsp; protected $primaryKey = "id";}如果你将 $incrementing 设置为 false,它会破坏它并始终返回 false,因为它告诉代码该 id 不是自动生成的,因此永远不会被获取。class User extends Model{&nbsp; public $incrementing = false;&nbsp; // ...}$user = new User;$user->save();dd($user->id);// null还要确保在迁移中启用 uuid 扩展<?phpclass AddUuidExtensionToPostgre extends Migration{&nbsp; &nbsp; public function up()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; DB::statement('CREATE EXTENSION IF NOT EXISTS "uuid-ossp";');&nbsp; &nbsp; }&nbsp; &nbsp; public function down()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; DB::statement('DROP EXTENSION IF EXISTS "uuid-ossp";');&nbsp; &nbsp; }}这是一个例子Schema::create('users', function (Blueprint $table) {&nbsp; &nbsp; $table->uuid('id');&nbsp; &nbsp; $table->primary('id');&nbsp; &nbsp; // ...});DB::statement('ALTER TABLE users ALTER COLUMN id SET DEFAULT uuid_generate_v4();');
打开App,查看更多内容
随时随地看视频慕课网APP