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

Rails 7中如何查询JSONB数组对象含指定邮箱的记录

查找JSONB数组列中包含指定邮箱的记录

在Rails 7中,针对Thread模型的participants(JSONB数组类型)列,要筛选出包含邮箱hakim@example.com的记录,你可以用以下几种基于PostgreSQL JSONB特性的实现方式:

方法一:数组展开+关联查询

通过jsonb_array_elements将数组展开为行记录,筛选匹配的邮箱后去重:

Thread.joins("JOIN jsonb_array_elements(threads.participants) AS p ON true")
      .where("p->>'email' = ?", "hakim@example.com")
      .distinct

方法二:EXISTS子查询

通过子查询判断是否存在匹配的参与者,无需额外去重:

Thread.where(
  "EXISTS (
    SELECT 1 FROM jsonb_array_elements(threads.participants) AS p
    WHERE p->>'email' = ?
  )", "hakim@example.com"
)

方法三:JSONB包含操作符

利用PostgreSQL的@>操作符,直接检查数组是否包含目标对象:

Thread.where("participants @> ?::jsonb", '[{"email": "hakim@example.com"}]')

以上三种方法都能准确筛选出目标记录,你可以根据实际场景选择最顺手的写法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 14:35:21