Hello.
I’m using the excellent Absinthe package, I’m trying to create a many to many association with an Index table, it looks like this:
defmodule Vulkan.Course do
use Vulkan.Web, :model
schema "courses" do
field :name, :string
field :description, :string
many_to_many :users, Vulkan.User, join_through: "user_courses"
timestamps()
end
.
.
.
end
defmodule Vulkan.User do
use Vulkan.Web, :model
schema "users" do
field :name, :string
field :handle, :string
field :email, :string
field :is_admin, :boolean, default: false
field :encrypted_password, :string
field :password, :string, virtual: true
many_to_many :courses, Vulkan.Course, join_through: "user_courses"
timestamps()
end
.
.
.
end
And the index looks like this:
defmodule Vulkan.UserCourse do
use Vulkan.Web, :model
schema "user_courses" do
belongs_to :user, Vulkan.User
belongs_to :course, Vulkan.Course
timestamps()
end
end
Just in case, the migration:
defmodule Vulkan.Repo.Migrations.CreateUserCourse do
use Ecto.Migration
def change do
create table(:user_courses) do
add :user_id, references(:users, on_delete: :nothing), null: false
add :course_id, references(:courses, on_delete: :nothing), null: false
timestamps()
end
create index(:user_courses, [:user_id])
create index(:user_courses, [:course_id])
create index(:user_courses, [:user_id, :course_id], unique: true)
end
end
Now my question is, how would I resolve the association? Should I create a type and resolve the association through it?
object :user_course do
field :id, :id
field :user_id, :id
field :course_id, :id
end
object :user do
field :id, :id
field :name, :string
field :handle, :string
field :email, :string
field :is_admin, :boolean
field :posts, list_of(:post), resolve: assoc(:posts)
field :courses, list_of(:course), resolve: assoc(:user_courses)
end
This approach doesn’t seem to work, because I’ve inserted a UserCourse
with user_id; 1
and course_id: 1
(both exist in the database) and when I run the query
query posts {
users {
id
name
courses {
id
name
}
}
}
I get the response
{
"data": {
"users": [
{
"name": "Andrés Pérez",
"id": "1",
"courses": null
},
{
"name": "Jon Doe",
"id": "2",
"courses": null
}
]
}
}
I can’t manage to find the docs for Absinthe-Ecto, so I’m quite lost.
How should I be doing it?
Any help is highly appreciated, thank you so much for your time.