Laravel中关联JSON类型数据透视表字段报错问题求助
问题解决:PostgreSQL JSON字段关联查询报错
问题原因
你用belongsToMany关联时,Laravel默认生成table2.unit_code = units.code的关联条件,但table2.unit_code是JSON类型,Unit模型的主键(假设是code字符类型)无法直接和JSON类型用=比较,PostgreSQL找不到对应运算符,因此抛出operator does not exist: character varying = json错误。
解决方案
根据table2.unit_code的存储结构,选择对应修改方式:
情况1:unit_code存单个字符串值(如"ABC123")
修改关联方法,用PostgreSQL的->>操作符提取JSON文本值,再和Unit主键比较:
public function workunit(){ return $this->belongsToMany('\App\Modules\Master\Unit\Model', 'table2', 'table1_id', 'unit_code') ->withPivot('anggaran') // 替换units为Unit模型实际表名,code为其主键字段,按需调整 ->whereRaw('table2.unit_code->>\'$\' = units.code'); }
也可以用Laravel原生的whereColumn写法:
public function workunit(){ return $this->belongsToMany('\App\Modules\Master\Unit\Model', 'table2', 'table1_id', 'unit_code') ->withPivot('anggaran') ->whereColumn('table2.unit_code->>\'$\'', '=', 'units.code'); }
情况2:unit_code存JSON数组(如["ABC123", "DEF456"])
要匹配数组中任意元素等于Unit主键,用ANY操作符转换类型后比较:
public function workunit(){ return $this->belongsToMany('\App\Modules\Master\Unit\Model', 'table2', 'table1_id', 'unit_code') ->withPivot('anggaran') ->whereRaw('units.code = ANY(table2.unit_code::text::varchar[])'); }
如果是jsonb类型字段,也可以用jsonb_contains:
public function workunit(){ return $this->belongsToMany('\App\Modules\Master\Unit\Model', 'table2', 'table1_id', 'unit_code') ->withPivot('anggaran') ->whereRaw('table2.unit_code @> to_jsonb(units.code::text)'); }
注意事项
- 替换代码中的
units和code为你实际的表名与主键字段。 - 确认
table2.unit_code的存储格式,单个值或数组对应选择合适的查询条件。
内容的提问来源于stack exchange,提问作者kel spk
相关产品推荐
相关产品推荐

