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

IHP框架中fetchOneOrNothing如何配合fetchRelated使用?

问题基础信息

涉及表结构

Posts:
id
roomsId

Rooms:
id

RoomEvents:
id
roomId
userId
created_at

查询代码

action MyAction { .. } = do
-- 省略其他逻辑
roomEvent <- query @RoomEvent
  |> filterWhere (#roomId, roomId)
  |> orderBy #createdAt
  |> fetchOneOrNothing
  >>= fetchRelated #userId

运行报错信息

Web/Controller/Posts.hs:150:21: error:
    • Could not deduce (FromRow fetchModel0)
        arising from a use of ‘fetchRelated’
      from the context: (?context::ControllerContext,
                         ?modelContext::ModelContext, ?theAction::PostsController)
        bound by the type signature for:
                   action :: (?context::ControllerContext,
                              ?modelContext::ModelContext, ?theAction::PostsController) =>
                             PostsController -> IO ()
        at Web/Controller/Posts.hs:57:5-10
      The type variable ‘fetchModel0’ is ambiguous
      These potential instances exist:
        instance Database.PostgreSQL.Simple.FromField.FromField a =>
                 FromRow (Only a)
          -- Defined in ‘Database.PostgreSQL.Simple.FromRow’
        instance FromRow Activity
          -- Defined at build/Generated/Types.hs:412:10
        instance FromRow ActivityPostFile
          -- Defined at build/Generated/Types.hs:802:10
        ...plus 64 others
        ...plus one instance involving out-of-scope types
        (use -fprint-potential-instances to see them all)
    • In the second argument of ‘(>>=)’, namely ‘fetchRelated #userId’

疑问解答

  1. 该错误不是其他表生成的实例干扰导致的。报错核心是编译器无法推断fetchRelated返回的关联模型类型,fetchModel0类型变量存在歧义,所以在匹配FromRow实例时找不到确定的目标。
  2. 单独更换fetchRelatedOrNothing或maybeFetchRelatedOrNothing无法解决问题,因为问题根源不在查询方法本身,而是类型推断链路断裂。

解决方案

检查对应视图的入参类型声明,错误是因为视图填写了错误的类型,导致类型系统倒推上游查询结果的类型时出现偏差,修改视图中的类型为正确值后问题会直接解决。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 12:15:03