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
)引用users
(id
))
PDOException ::(“SQLSTATE [HY000]:常规错误:1215无法添加外键约束”)
PDOStatement对象::执行()