为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
梦里花落0921 2023-06-24 15:09:42
我有一个以下身份验证表:<?phpuse 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');    }}这是模型:<?phpnamespace 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);    }}
查看完整描述

1 回答

?
慕工程0101907

TA贡献1887条经验 获得超5个赞

只需确保强制转换为字符串且主键名称正确


namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model

{

  protected $casts = [

    'id' => 'string'

  ];

  protected $primaryKey = "id";

}

如果你将 $incrementing 设置为 false,它会破坏它并始终返回 false,因为它告诉代码该 id 不是自动生成的,因此永远不会被获取。


class User extends Model

{

  public $incrementing = false;

  // ...

}


$user = new User;

$user->save();

dd($user->id);

// null

还要确保在迁移中启用 uuid 扩展


<?php


class AddUuidExtensionToPostgre extends Migration

{


    public function up()

    {

        DB::statement('CREATE EXTENSION IF NOT EXISTS "uuid-ossp";');

    }


    public function down()

    {

        DB::statement('DROP EXTENSION IF EXISTS "uuid-ossp";');

    }

}

这是一个例子



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

    $table->uuid('id');

    $table->primary('id');

    // ...

});


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


查看完整回答
反对 回复 2023-06-24
  • 1 回答
  • 0 关注
  • 126 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信