Laravel Eloquent with()方法在PostgreSQL下报错求助
Laravel Eloquent 结合PostgreSQL使用with()预加载关联报错:uuid = integer 运算符不存在
在Laravel 10.7.1 + PHP 8.1.17 + PostgreSQL环境下,调用Eloquent的with()方法预加载关联模型时触发如下错误:
SQLSTATE[42883]: Undefined function: 7 ERROR: operator does not exist: uuid = integer LINE 1:
但使用$modelParent->parentChilds()->createMany([...data])创建关联数据时无报错。
表结构
parents -------- id (uuid) name (string) user_id (uuid) description (text) details --------- id (uuid) parent_id (uuid) title (string) description (tinytext)
控制器代码
/** * Display the specified resource. */ public function show(string $id) { $this->authorize('viewParent', \App\Models\Parent::class); $model = \App\Models\Parent::with(['user', 'parentChilds'])->findOrFail($id); return view("$this->view.show", [ 'model' => $model, 'title' => "$this->title", 'route' => $this->route, ]); }
Parent模型代码
/** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'title', 'user_id', 'description', ]; /** * The attributes that should be cast to native types. * * @var array */ protected $casts = [ 'id' => 'string', ]; /** * Get the user that owns the MinuteOfMeeting * * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function user(): BelongsTo { return $this->belongsTo(User::class, 'user_id')->withTrashed(); } /** * Get all of the minuteOfMeetingDetails for the MinuteOfMeeting * * @return \Illuminate\Database\Eloquent\Relations\HasMany */ public function parentChilds(): HasMany { return $this->hasMany(ParentChild::class, 'parent_id', 'id'); }
错误的Child模型代码
/** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'parent_id', 'title', 'description' ]; /** * The attributes that should be cast to native types. * * @var array */ protected $casts = [ 'id' => 'string', 'parent_id' => 'string', ]; /** * Get the minuteOfMeeting that owns the MinuteOfMeetingDetail * * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function parent(): BelongsTo { return $this->belongsTo(Parent::class, 'parent', 'id')->withTrashed(); }
错误原因
Child模型的parent()关联方法中,belongsTo的外键参数错误,传入了'parent',但实际表中存储关联的字段是parent_id。当Laravel执行预加载查询时,会尝试用不存在的parent字段(默认被识别为integer类型)去关联parents表的uuid类型id字段,导致PostgreSQL抛出类型不匹配的运算符错误。
而createMany()方法正常是因为该方法从Parent模型的parentChilds()关联出发,使用正确的parent_id外键写入数据,不会触发反向关联的查询逻辑。
修复方案
修改Child模型的parent()关联方法,将外键参数改为'parent_id':
/** * Get the minuteOfMeeting that owns the MinuteOfMeetingDetail * * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function parent(): BelongsTo { return $this->belongsTo(Parent::class, 'parent_id', 'id')->withTrashed(); }
内容的提问来源于stack exchange,提问作者Zulfikar Ditya
相关产品推荐
相关产品推荐

