如何在Hausra中以Rails风格实现多态关联查询
在Hasura中实现基于多态关联的Rails风格GraphQL查询
前提说明
现有三张数据表,其中pictures为多态表,建表语句如下:
CREATE TABLE pictures ( id serial, imageable_type text not null, imageable_id integer not null, name text, -- 注:原建表语句未包含该字段,但目标查询需返回该字段,故补充 comment on table pictures is 'imageable_id belongs to users.id and products.id' ); CREATE TABLE users ( id serial, name text ); CREATE TABLE products ( id serial, name text );
需求是在Hasura中以Rails风格(无需数据库外键)执行以下GraphQL查询:
{ products { name pictures { id name } } }
实现步骤
1. 在Hasura中创建多态关联
Rails的多态关联通过[关联类型]_type和[关联类型]_id字段实现,这里对应imageable_type和imageable_id。我们需要为products表创建数组关系:
- 打开Hasura控制台,进入Data标签页,选择
products表 - 切换到Relationships子标签,点击Add Relationship
- 配置关系:
- 关系名称:
pictures(与目标查询中的字段名一致) - 关系类型:Array Relationship(一个产品对应多张图片)
- 关联规则:
- 从
products.id关联到pictures.imageable_id - 添加匹配条件:
pictures.imageable_type = 'Product'(Rails中多态类型通常为模型类名的字符串)
- 从
- 关系名称:
- 点击Save完成创建
2. 执行目标查询
进入Hasura的GraphQL控制台,直接输入目标查询语句并执行即可得到结果:
{ products { name pictures { id name } } }
注意事项
- 确保
pictures表中存储的imageable_type值与配置的匹配条件一致(比如产品对应的图片记录需将imageable_type设为'Product') - 若
pictures表原本没有name字段,需先通过DDL语句添加该字段才能在查询中返回
内容的提问来源于stack exchange,提问作者Dishant Rana
相关产品推荐
相关产品推荐

