graphql - 用苦艾酒在 GraphQL 中表示 Elixir/Ecto 关联
问题描述
我已经为我的几个模型添加了多对多关联,并且它似乎在隔离时工作得很好——这意味着没有 GraphQL 模式声明。这是我的一个模型的代码:
use Ecto.Schema
import Ecto.Changeset
alias Trader.Collect.Card
schema "users" do
field(:email, :string)
field(:first_name, :string)
field(:last_name, :string)
field(:password, :string)
field(:username, :string)
many_to_many(:cards, Card, join_through: "user_cards")
timestamps()
end
@doc false
def changeset(user, attrs) do
user
|> cast(attrs, [:first_name, :last_name, :email, :username, :password])
|> validate_required([:first_name, :last_name, :email, :username, :password])
end
end
这是 GraphQL 类型声明:
defmodule TraderWeb.Schema.Types.User do
use Absinthe.Schema.Notation
@desc "User model representation"
object :user do
field(:id, non_null(:id))
field(:first_name, non_null(:string))
field(:last_name, non_null(:string))
field(:username, non_null(:string))
field(:email, non_null(:string))
field(:password, non_null(:string))
# field(:cards, list_of(:card), resolve: assoc(:cards))
end
end
这是 Absinthe/GraphQL 部分的顶级架构定义:
defmodule TraderWeb.Schema.Schema do
use Absinthe.Schema
import_types(Absinthe.Type.Custom)
# Import Types individually here
import_types(TraderWeb.Schema.Types.{
User,
Card,
CardSet
})
# import queries here
import_types(TraderWeb.Schema.Queries.{
User,
Card,
CardSet
})
query do
import_fields(:user_queries)
import_fields(:card_queries)
import_fields(:card_set_queries)
end
end
请注意,卡片字段在类型中被注释掉。在这种情况下一切正常,但是,如果我取消注释该卡字段,我会收到以下错误:
== Compilation error in file lib/trader_web/schema/types/user.ex ==
** (CompileError) lib/trader_web/schema/types/user.ex:12: undefined function assoc/1
(elixir) src/elixir_locals.erl:108: :elixir_locals."-ensure_no_undefined_local/3-lc$^0/1-0-"/2
(elixir) src/elixir_locals.erl:108: anonymous fn/3 in :elixir_locals.ensure_no_undefined_local/3
(stdlib) erl_eval.erl:670: :erl_eval.do_apply/6
(elixir) lib/kernel/parallel_compiler.ex:229: anonymous fn/4 in Kernel.ParallelCompiler.spawn_workers/7
我已经非常积极地用谷歌搜索了这个问题,但找不到任何东西。目前还不清楚该assoc
功能甚至存在于何处——它是一个 ecto 的东西吗?还是苦艾酒?我还在某处找到了示例代码,dataloader
但我根本无法让它工作。
我感谢你们所有人的任何想法和想法!谢谢
解决方案
您将需要(已弃用)Absinthe.Ecto包,或使用新的Dataloader。Absinthe 文档中有一个关于 Ecto 最佳实践的部分,其中描述了使用数据加载器的新语法https://hexdocs.pm/absinthe/ecto.html#dataloader。因为这也需要添加到您的上下文中,所以在这里添加完整的设置会太多,但是文档非常好。
推荐阅读
- javascript - 如何使用 preact 创建页面转换
- java - 为什么 java LONG_MAX 与 vue axios 数据不一样??如何解决?
- java - 从字节数组解码 Avro 文件
- python - Python:如果值不是预期的,那么发出警报的正确方法是什么?
- python - 无法在 Pyqt5 应用程序中导出 Folium 绘制多边形上的坐标
- ckan - CKAN 登录重定向到缺少 root_path 的 URL
- php - php / 正则表达式将多个段落转换为一个带有换行符的段落
- join - 在 Cakephp4 中加入查询只返回一个表数据
- javascript - 随机选项如何捕捉通讯号码?
- mochawesome - Invalid value null error for mochawesome-report-generator