Laravel Eloquent hasOne关联返回非匹配关联模型问题如何解决
异常原因
Laravel Eloquent默认假设模型主键是自增整数类型,会自动将主键值强制转换为整数处理。
你的User模型将steamid设为主键,该字段是长度超过PHP整数上限(32位PHP最大为2147483647,64位PHP最大为9223372036854775807)的字符串,强制转整数时会发生精度丢失,导致76561198048535340和76561198048535341两个不同的字符串被转为同一个整数值,关联查询时就匹配到了错误的customtag记录。
反向关联查询时没有返回错误结果,是因为当前测试的customtag记录没有对应匹配的user,所以返回空结果符合你的预期,本质上也存在同样的类型转换问题。
解决方法
在User模型中添加两个属性配置,关闭主键自增、指定主键类型为字符串即可:
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\HasOne; class User extends Model { public $timestamps = false; public $primaryKey = "steamid"; // 新增以下两行配置 public $incrementing = false; protected $keyType = 'string'; public function customtag(): HasOne { return $this->hasOne(Customtag::class, "steamid", "steamid"); } }
如果后续需要用steamid作为关联键进行其他查询,建议也在Customtag模型中对steamid字段做类型转换声明,避免后续查询出现类似问题:
// 在Customtag类中添加 protected $casts = [ 'steamid' => 'string' ];
内容的提问来源于stack exchange,提问作者Joram
相关产品推荐
相关产品推荐

