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

如何在Ecto查询中获取Money.Ecto.Composite.Type类型的属性?

解决方案

针对你遇到的问题,核心原因是Ecto查询语法会把payment.amount.currency_code()解析为尝试访问名为currency_code的字段,而非调用Elixir方法。以下是几种可行的解决方式:

  • 直接访问复合类型的子属性
    Money.Ecto.Composite.Type对应数据库中的复合类型(比如PostgreSQL的复合类型),可以直接通过点号访问其内部属性,无需加括号:

    query =
      from(
        payment in Payment,
        where: payment.amount.currency_code == ^currency
      )
    
  • 使用fragment手动编写SQL
    如果Ecto自动解析复合类型子属性失败,可通过fragment显式指定SQL逻辑:

    query =
      from(
        payment in Payment,
        where: fragment("(?).currency_code", payment.amount) == ^currency
      )
    
  • 使用ex_money提供的查询辅助函数
    ex_money v5.x版本封装了Ecto查询辅助模块,导入后可直接用现成的过滤函数:

    import Money.Ecto.Query
    
    query =
      from(payment in Payment)
      |> where_currency(:amount, ^currency)
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 12:05:21