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

如何在IHP中处理复杂查询结果无需手动指定列

实现方案

完全可以实现你要的效果,核心是直接复用IHP自动为Post模型生成的FromRow实例,不需要手动拆分posts表的单个字段。

完整实现代码如下:

  1. 自定义复合类型(你提出的结构无需修改)
data PostWithCommentsCount = PostWithCommentsCount
    { post :: Post
    , commentsCount :: Int
    }
    deriving (Eq, Show)
  1. 实现FromRow实例
instance FromRow PostWithCommentsCount where
    fromRow = PostWithCommentsCount <$> fromRow <*> field
  1. 编写查询函数
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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 15:45:00