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

Hasura查询多关联表记录数的问题与解决方案

Hasura GraphiQL 查询关联表聚合统计报错解决方法

问题场景

需要在Hasura的GraphiQL中编写查询,获取所有用户的基础数据,同时统计每个用户对应的:

  • follow表中的关注数(is_follow=1)
  • analytics表中的访问数(type='visit')和分享数(type='share')

最初编写的查询语句如下:

query getAllUsersData {
  users {
    id
    username
    bio
    first_name
    last_name
    banner
    profile_image_url
    created_at
    followers: follow_aggregate(where: {user_id: {_eq: id}, is_follow: {_eq: 1}}) {
        aggregate {
          count: count
        }
      }
      visits: analytics_aggregate(where: {user_id: {_eq: id}, type: {_eq: "visit"}}) {
        aggregate {
          count: count
        }
      }
      shares: analytics_aggregate(where: {user_id: {_eq: id}, type: {_eq: "share"}}) {
        aggregate {
          count: count
        }
      }
  }
}

运行后报错:

Cannot query field "follow_aggragate" and "analytics_aggregate" on type "users"

对应的期望SQL逻辑为:

SELECT u.id, u.username, u.bio, u.first_name, u.last_name, u.banner, u.profile_image_url, u.created_at,
       COUNT(f.user_id) AS followers,
       SUM(CASE WHEN a.type = 'visit' THEN 1 ELSE 0 END) AS visits,
       SUM(CASE WHEN a.type = 'share' THEN 1 ELSE 0 END) AS shares
FROM user u
LEFT JOIN follow f ON u.id = f.user_id
LEFT JOIN analytics a ON u.id = a.user_id
GROUP BY u.id

报错原因

Hasura中的xxx_aggregate聚合字段并非自动存在,必须基于已配置并跟踪的表间关系生成。最初的查询直接使用follow_aggregate和analytics_aggregate,但此时users表与follow、analytics表之间没有建立对应关系,Hasura无法识别这些字段。

解决方法

  1. 配置数据库外键:确保follow表的user_id字段外键关联users表的id字段,analytics表的user_id字段同样关联users.id。
  2. 在Hasura中跟踪关系:进入Hasura控制台,分别在users表的「关系」页面,生成与follow、analytics表的数组关系(默认生成的关系名称通常为follows、analytics)。
  3. 修改查询语句:利用Hasura自动生成的聚合字段,无需再手动指定user_id: {_eq: id}——因为已配置的关系会自动关联当前用户ID。

最终可用查询语句

query getAllUsersData {
 users {
   id
   username
   bio
   first_name
   last_name
   banner
   profile_image_url
   created_at
   followers: follows_aggregate(where: {is_follow: {_eq: 1}}) {
       aggregate {
         count: count
       }
     }
     visits: analytics_aggregate(where: {type: {_eq: "visit"}}) {
       aggregate {
         count: count
       }
     }
     shares: analytics_aggregate(where: {type: {_eq: "share"}}) {
       aggregate {
         count: count
       }
     }
 }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 04:05:40