You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel中如何用HasJsonRelationships关联JSON数组型Operator ID?

问题:通过JSON数组ID关联HasManyJson获取Operator数据

我当前有一个字段名为operators的列,存储的是JSON数组格式的数据(示例值:[1, 2, 3]),数组中的每个数字对应operators表中的主键ID。我希望借助HasJsonRelationships扩展来建立关联,获取对应的Operator模型数据,但目前查到的用法都是针对数组中存储对象的场景,自己尝试的几种写法均报错。


尝试的写法及报错

尝试1

public function operators(): HasManyJson
{
    return $this->hasManyJson(Operator::class, 'operators[]');
}

尝试2

public function operators(): HasManyJson
{
    return $this->hasManyJson(Operator::class, 'operators[]->id');
}

报错信息:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'operators.operators' in 'where clause'

生成的SQL语句:

select * from `operators` where (1 member of(json_extract(`operators`.`operators`, '$[*]."id"')))

尝试3

public function operators(): HasManyJson
{
    return $this->hasManyJson(Operator::class, 'operators');
}

报错信息:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'operators.operators' in 'where clause'

生成的SQL语句:

select * from `operators` where (1 member of(`operators`.`operators`))

正确写法

问题出在关联参数的传递逻辑上,hasManyJson的第二个参数需要指定当前模型表中存储JSON数组的字段名,同时通过第三个参数明确目标模型的主键字段(与数组内ID匹配)。

use Illuminate\Database\Eloquent\Relations\HasManyJson;

public function operators(): HasManyJson
{
    return $this->hasManyJson(Operator::class, 'operators', 'id');
}

说明

  • 第二个参数'operators':当前模型表中存储JSON ID数组的字段名;
  • 第三个参数'id':operators表中与数组内ID匹配的主键字段;
  • 该写法会生成正确的SQL逻辑,检查operators表的id是否存在于当前模型的operators JSON数组中。

内容的提问来源于stack exchange,提问作者Niklas Forst

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 15:22:16