[英]Representing Elixir/Ecto associations in GraphQL with absinthe
我已經為我的幾個模型添加了多對多的關聯,並且它似乎在隔離中運行良好——這意味着沒有 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
找到了示例代碼,但我根本無法dataloader
工作。
我感謝你們的任何想法和想法! 謝謝
您將需要(已棄用) Absinthe.Ecto包,或者使用新的Dataloader 。 Absinthe on Ecto 最佳實踐的文檔中有一節介紹了使用 dataloader https://hexdocs.pm/absinthe/ecto.html#dataloader的新語法。 由於這還需要添加到您的上下文中,因此在此處添加完整的設置太多了,但文檔非常好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.