如何在IHP中处理复杂查询结果无需手动指定列
实现方案
完全可以实现你要的效果,核心是直接复用IHP自动为Post模型生成的FromRow实例,不需要手动拆分posts表的单个字段。
完整实现代码如下:
- 自定义复合类型(你提出的结构无需修改)
data PostWithCommentsCount = PostWithCommentsCount { post :: Post , commentsCount :: Int } deriving (Eq, Show)
- 实现
FromRow实例
instance FromRow PostWithCommentsCount where fromRow = PostWithCommentsCount <$> fromRow <*> field
- 编写查询函数
fetchPostsWithCommentsCount :: (?modelContext :: ModelContext) => IO [PostWithCommentsCount] fetchPostsWithCommentsCount = do trackTableRead "posts" -- 如果需要comments表变更时也触发自动刷新,可补充下面这行 -- trackTableRead "comments" sqlQuery "SELECT posts.*, (SELECT COUNT(*) FROM comments WHERE comments.post_id = posts.id) AS comments_count FROM posts" ()
注意事项
- 必须保证SQL返回列的顺序和
PostWithCommentsCount的字段顺序完全匹配:先返回posts.*(完整的posts表所有字段,刚好适配Post类型的解析逻辑),再返回额外的comments_count字段 - 后续
posts表结构变更后,IHP会自动更新生成的Post类型和对应的FromRow实例,以上代码不需要做任何修改就能自动适配新结构,大幅降低维护成本
内容的提问来源于stack exchange,提问作者stianlagstad
相关产品推荐
相关产品推荐

