在用户表上使用UUID作为主键会导致PDOEXCEPTION错误

时间:2018-03-15 22:14:09

标签: laravel laravel-5 laravel-5.2

Uuids.php - 为用户ID

生成uuid
<?php

namespace App\Traits;

use Ramsey\Uuid\Uuid;

use Ramsey\Uuid\Exception\UnsatisfiedDependencyException;

trait Uuids
{

    // Boot function from laravel.
    protected static function boot()
    {
        parent::boot();

        static::creating(function ($model) {
            $model->{$model->getKeyName()} = Uuid::uuid1()->toString();
        });
    }

}

-

用户架构

Schema::create('users', function (Blueprint $table) {
        // $table->increments('id');
        $table->uuid('id');
        $table->primary('id');
    });

-

发布架构

Schema::create('posts', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id')->unsigned();
        $table->foreign('user_id')->references('id')->on('users');
    });

用户模型

<?php

namespace App;

use Uuids;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    public $incrementing = false;

}

我在运行php artisan migrate时遇到的错误

:SQLSTATE [HY000]:常规错误:1215无法添加外键约束(SQL:alter table posts添加约束posts_user_id_foreign外键(user_id)引用usersid))

PDOException ::(“SQLSTATE [HY000]:常规错误:1215无法添加外键约束”)

PDOStatement对象::执行()

0 个答案:

没有答案