I am using absinthe with elixir (phoenix 1.3). I have a blog app that has Users, Posts, and Likes, and the likes are joined with a many-to-many relationship between Users and Posts.
schema "users" do
field :email, :string
field :handle, :string
many_to_many :liked_posts, MyApp.Content.Post, join_through: "likes"
end
schema "posts" do
field :title, :string
field :content, :string
many_to_many :liking_users, MyApp.Accounts.User, join_through: "likes"
end
schema "likes" do
belongs_to :user, MyApp.Accounts.User
belongs_to :post, MyApp.Content.Post
end
Let’s say I want to aggregate them on the backend rather than the front. I would like :liked_by to simply be a count of all the likes that exist, more like field :likes, :int, so that I can get back responses like this:
{
"data": {
"post" : {
"title" : "Title",
"content" : "This is the content",
"likes" : 7
}
}
}
What would my object have to look like? I want to do something like this:
object :post do
field :id, :integer
field :title, :string
field :content, :string
field :likes, :integer, resolve: assoc(:liking_users, fn query, id, _ ->
query |> from like in MyApp.Content.Like, where: like.post_id == ^id, select: count("*")
)
end