Laravel - "Operator does not exist" 使用 UUID 密钥获取相关模型时出现异常

Laravel - "Operator does not exist" exception when fetching a related model with an UUID key

我 运行 在使用 Laravel 8 应用程序时遇到问题。我有两个模型,UserPostPost 属于 User.

两种模型都将 UUID 作为主键,并且是这样建模的(使用 PostgreSQL):

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

        Schema::create('posts', function (Blueprint $table) {
            $table->uuid('id')->primary();
            $table->uuid('user_id');

            $table->foreign('user_id')->references('id')->on('users');
        });

关系定义如下:

    // Post.php

    public function user()
    {
        return $this->belongsTo(\App\Models\User::class);
    }

两个模型也有 public $incrementing = false 来解释 UUID。

PostsController 获取一些帖子及其相关用户:

    public function index()
    {
        $posts = Post::with('user')->paginate(10);
    }

然而,这引发了以下异常:

SQLSTATE[42883]: Undefined function: 7 ERROR: operator does not exist: uuid = integer LINE 1: select * from "users" where "users"."id" in (3) ^ HINT: No operator matches the given name and argument types. You might need to add explicit type casts. (SQL: select * from "users" where "users"."id" in (3)) 

Laravel 将用户 ID 视为整数(注意 3,数据库中唯一的用户 ID 以 3a6bc3c3... 开头)。但是我似乎找不到根本原因,也找不到解决方法。

有什么想法吗?

谢谢!

您可能还想将 protected $keyType 设置为 Model 它设置为 int:

protected $keyType = 'string';

"If your primary key is not an integer, you should set the protected $keyType property on your model to string"

Laravel 8.x Docs - Eloquent - Model Conventions - Primary Keys