刚接触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.

《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
讨论数量: 6

$table->unsignedBigInteger('uuid');

这个类型错了吧,要 string

2年前 评论
如果希望她不会走 (楼主) 2年前
MArtian 2年前
OrangBus

$table->uuid('uuid');

2年前 评论

直接贴下你的表结构 检查是不是数据类型的长度不一致导致的 检查是否乱码。更改统一的字符类型,比如更改字符类型为utf8;

2年前 评论

Users migrtion

$table->uuid('id')->primary();

User model

public $incrementing = false;

protected static function booted()
{
    // 模型创建是自动填充 UUID 主键
    static::creating(function (Model $model) {
        $model->setAttribute($model->getKeyName(), Str::orderedUuid()->toString());
    });
}

另外提醒一下,最好用 Str::orderedUuid() 来生成可排序的 UUID!!!

2年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!