You need to enable JavaScript to run this app. Laravel Eloquent以UID为主键时使用::with关联查询报错如何解决
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.22 02:12:14