Hasura查询中执行聚合查询时能否避免重复编写where条件
Hasura同请求下列表与聚合查询复用where过滤条件方案
存在可落地的简洁实现,核心是通过GraphQL变量统一承载where条件,完全不需要重复写两份过滤逻辑。
实现逻辑
Hasura会为每张可查询的表自动生成对应的布尔表达式输入类型,命名规则是[表名]_bool_exp。你示例里用的v4_bo_v_attribute_values表,对应的类型就是v4_bo_v_attribute_values_bool_exp,这个类型可以同时传给列表查询、聚合查询的where参数。
你只要把完整的where过滤条件声明为这个类型的变量,两个查询字段直接引用同一个变量就行,不用在查询语句里重复写一遍过滤规则。
优化后的查询写法
query getAttributeValues( $language_code: String $id_attribute: Int $search: String $where: v4_bo_v_attribute_values_bool_exp! ) { v4_bo_v_attribute_values( where: $where order_by: { attribute_value_translation: asc, attribute_value: asc } limit: 100 ) { attribute_value attribute_value_translation } v4_bo_v_attribute_values_aggregate(where: $where) { aggregate { count } } }
调用接口时只需要构造一次where条件对象,作为$where变量传入即可,示例传参如下:
{ "id_attribute": 1, "language_code": "zh-CN", "search": "关键词", "where": { "_and": [ { "id_attribute": { "_eq": 1 } }, { "_or": [{ "language_code": { "_eq": "zh-CN" } }, { "language_code": { "_is_null": true } }] }, { "_or": [{ "attribute_value_translation": { "_ilike": "关键词" } }, { "attribute_value": { "_ilike": "关键词" } }] } ] } }
注意点
- GraphQL本身不支持在入参位置(比如where参数)用Fragment,别尝试用Fragment抽离where逻辑,变量复用是Hasura场景下的标准可行方案。
- 这种写法后续改过滤规则的时候,只需要调整一次传入的
$where变量内容就行,不会出现两处条件写得不一致的问题。
内容的提问来源于stack exchange,提问作者Stéphane Gerber
相关产品推荐
相关产品推荐

