我刚刚开始学习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))"
发布于 2018-01-19 13:11:43
您还需要生成UUID --与自动递增无符号整数键不同的是,UUID字段不只是填充自身。
其中一个流行且使用非常简单的软件包是alsofronie/雄辩-uuid,在这里可以获得:https://github.com/alsofronie/eloquent-uuid。
发布于 2021-06-15 02:37:24
我所做的就是为使用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
}
所以你不必每次创造新的东西。
https://stackoverflow.com/questions/48349505
复制