字段 'id' 没有默认值 Laravel 中的 UUID 字段

Field 'id' doesn't have a default value for UUID Field in Laravel

刚开始学习laravel。我熟悉CakePHP

我曾经在我的数据库和 CakePHP 中使用 UUID 字段作为主键,只需将列字段的数据类型更改为 CHAR(36) 就非常简单并且效果很好。

在Laravel中,我修改了users迁移,将increments更改为uuid字段并设置为primary key

创建用户表

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->uuid('id');
            $table->primary('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });

        Schema::table('users', function (Blueprint $table) {
            $table->string('first_name')->nullable();
            $table->string('last_name')->nullable();
            $table->uuid('role_id');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}

但是,当我保存一条新记录时,出现错误

Illuminate\Database\QueryException thrown with message
"SQLSTATE[HY000]: General error: 1364 Field 'id' doesn't have a default value 
(SQL: insert into `users` (`name`, `email`, `password`, `updated_at`, `created_at`) 
values (Anuj, anuj@example.com, password_hash, date-time, date-time))"

您还需要生成 UUID - 与自动递增无符号整数键不同,UUID 字段不会自行填充。

一个流行且非常易于使用的此类软件包是 alsofronie/eloquent-uuid,可在此处获得:https://github.com/alsofronie/eloquent-uuid

我为此所做的是为使用 UUID 的模型创建特征:

trait WithUuid
{
    public static function boot()
    {
        parent::boot();

        self::creating(function ($model) {
            $model->{$model->getKeyName()} = (string) Uuid::generate(4);
        });
    }

    public function initializeHasUuid()
    {
        $this->incrementing = false;
        $this->keyType = 'string';
    }
}

然后在您的模型上声明特征:


class User extends Model
{
    use WithUuid;

   // rest of your Code
}

所以你不必每次创建一个新的。