Laravel Eloquent以UID为主键时使用::with关联查询报错如何解决
问题原因
Laravel默认所有模型的主键为自增整型,会自动对主键值做整型强制转换。你使用UID(字符串类型的唯一标识)作为主键,未在模型中配置主键相关属性,导致Eloquent提取BinaryUid值0607B8E6-A7AE-EB11-80FB-0050562E716F时,强制转整型得到了607,最终触发SQL类型不匹配报错。
解决方案
分别在三个模型中添加主键配置,关闭自增、指定主键名和主键类型为字符串即可:
1. Binary模型
class Binary extends Model { // 新增以下三个配置 protected $primaryKey = 'BinaryUid'; public $incrementing = false; protected $keyType = 'string'; // 原有关联逻辑保持不变 public function templates() { return $this->belongsToMany(Template::class,'TemplateBinary','BinaryUid','TemplateUid','BinaryUid','TemplateUid'); } }
2. Template模型
class Template extends Model { // 新增以下三个配置 protected $primaryKey = 'TemplateUid'; public $incrementing = false; protected $keyType = 'string'; // 原有关联逻辑保持不变 public function binaries() { return $this->hasManyThrough(Binary::class,TemplateBinary::class,'TemplateUid','BinaryUid','TemplateUid','BinaryUid'); } }
3. TemplateBinary Pivot模型
class TemplateBinary extends Pivot { // 新增以下三个配置 protected $primaryKey = 'TemplateBinaryUid'; public $incrementing = false; protected $keyType = 'string'; // 其他原有逻辑保持不变 }
修改完成后重新执行Binary::with('templates')->get()即可正常返回结果。
内容的提问来源于stack exchange,提问作者varo90
相关产品推荐
相关产品推荐

