刚接触Laravel遇到关于UUID的一些疑问。
1. 运行环境
1). 当前使用的 Laravel 版本?
使用Laravel版本: 8.X
2). 当前使用的 php/php-fpm 版本?
PHP 版本:7.3
php-fpm 版本:
3). 当前系统
Windows 11
Laragon 集成环境
4). 业务环境
开发环境
5). 相关软件版本
Mysql 5.7
Nginx 1.19
2. 问题描述?
以下是我自定义的一个异常,主要是在学习使用UUID作用ID外键时遇到的一个问题。
在社区寻找挺久答案了,流程也是按照社区来的
{
"msg": "异常啦!",
"data": {
"type": "PDO",
"error_code": "01000",
"error_msg": "SQLSTATE[01000]: Warning: 1265 Data truncated for column 'uuid' at row 1 (SQL: insert into `users` (`name`, `password`, `email`, `uuid`, `updated_at`, `created_at`) values (nihao12333, $2y$10$1z/tLw8NpviVxegNvS/iROI3oV1RCsvgw7C3BRvmaWqJSSnsYgqzK, 123456@qq.com, 4d2b8da9-5c58-4cc8-b002-9c6bc2b120cb, 2022-02-19 19:58:45, 2022-02-19 19:58:45))"
},
"code": 101,
"timestamp": 1645271925
}
完整的Users
表迁移文件如下:
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name')->default('')->comment('用户名');
$table->string('password')->default('')->comment('密码');
$table->string('nickname')->default('')->comment('昵称');
$table->integer('points')->default('0')->comment('积分');
$table->unsignedBigInteger('uuid');
$table->foreign('uuid')->references('id')->on('users');
$table->string('email')->default('')->comment('邮箱');
$table->timestamps();
});
}
完整的 Controller
方法:
public function Register(Request $request)
{
$user = New User();
$user->name = $request->username;
$user->password = bcrypt($request->password);
$user->email = $request->email;
$user->uuid =\Str::uuid();
$user->save();
return response()->json($user);
}
在一步步按照社区的文档教程后进行自己的实际操作,发现不能被写入到数据库,而使用foreignUuid
后可被写入且会自动隐藏id
字段,一旦后面增加了 references
或者constrained
参数也会无法被写入 进而提示Data truncated for column 'uuid' at row 1
各位大佬是否给一个可供参考的实例或者是一个思路,也是才接触Laravel.
$table->unsignedBigInteger('uuid');
这个类型错了吧,要 string
$table->uuid('uuid');
直接贴下你的表结构 检查是不是数据类型的长度不一致导致的 检查是否乱码。更改统一的字符类型,比如更改字符类型为utf8;
Users migrtion
User model
另外提醒一下,最好用
Str::orderedUuid()
来生成可排序的 UUID!!!