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

时间:2018-01-19 21:04:16

标签: laravel laravel-5 laravel-migrations

我刚开始学习laravel。我熟悉CakePHP

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

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

CreateUserTable

<?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))"

2 个答案:

答案 0 :(得分:3)

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

一个流行且非常简单易用的软件包是alsofronie / eloquent-uuid,可在此处找到:Python 3.5.4 documentation

答案 1 :(得分:0)

我为此所做的是为使用 UUID 的模型创建一个 Trait:

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';
    }
}

然后在您的模型上声明 Trait:


class User extends Model
{
    use WithUuid;

   // rest of your Code
}

因此您不必每次创建内容时都创建一个新的。

相关问题