【问题标题】:How do I set up an Absinthe schema with field names different than underlying Ecto field names?如何设置字段名称与基础 Ecto 字段名称不同的 Absinthe 架构?
【发布时间】:2018-06-30 01:01:57
【问题描述】:

例如,我想在以下 Absinthe 架构中调用前端的 inserted_on 时间戳 created_at

defmodule MyAppWeb.Schema.AccountTypes do
  use Absinthe.Schema.Notation

  object :user do
    field :id, :id
    field :email, :string
    field :inserted_on, :datetime
  end
end

但我不确定如何设置 Ecto Absinthe 映射。我应该在我的 Ecto 架构中添加一个虚拟字段吗?

【问题讨论】:

    标签: ecto absinthe


    【解决方案1】:

    一种选择是在 Ecto 模式中为数据库字段使用 :source 选项,这样您就可以使用自己的内部名称:

    defmodule MyAppWeb.Schema.AccountTypes do
      use Absinthe.Schema.Notation
    
      object :user do
        field :id, :id
        field :email, :string
        field :created_at, :datetime, source: :inserted_on
      end
    end
    

    但最好的选择可能是在查询宏中设置正确的字段名称:

    defmodule My.Schema do
      use Absinthe.Schema
      query do
        field :created_at, :string do
          resolve &MyResolver.inserted_on/3
      end
    end
    

    .. 或使用您自己的数据类型而不是字符串..

    【讨论】:

    • 我尝试了第一个解决方案(当然,应用于我的数据结构),但得到了这个错误:` ** (KeyError) key :source not found expand struct:: Absinthe.Type.Field。 __struct__/1` 这个source 选项是否可能已从苦艾酒中删除?
    • 这是一个相对较新的功能,所以也许检查你的ecto版本。此处描述:hexdocs.pm/ecto/Ecto.Schema.html#field/3
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多