我在使用 Laravel 8 应用程序时遇到了问题。我有两个模型,User
和Post
.Post
属于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(AppModelsUser::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
,数据库中唯一的用户具有以3a6bc3c3...
开头的id)。但是,我似乎找不到根本原因或解决此问题的方法。
有什么想法吗?
谢谢!
您可能还想将protected $keyType
设置为 onModel
设置为int
:
protected $keyType = 'string';
"如果主键不是整数,则应将模型上的受保护
$keyType
属性设置为string
">
Laravel 8.x 文档 - 雄辩 - 模型约定 - 主键