jeudi 15 mars 2018

Using UUID as primary key on users table causes PDOEXCEPTION error

Uuids.php - Generate a uuid for the user id

<?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();
        });
    }

}

-

User Schema

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

-

Post Schema

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

User's Model

<?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;

}

Errors I'm getting when I run php artisan migrate

: SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table posts add constraint posts_user_id_foreign foreign key (user_id) references users (id))

PDOException::("SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint")

PDOStatement::execute()



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire