我正在使用苦艾酒和长生不老药(凤凰 1.3)。我有一个博客应用程序,其中包含用户、帖子和喜欢,并且喜欢通过用户和帖子之间的多对多关系加入。
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
假设我想在后端而不是前端聚合它们。我想:liked_by
简单地计算所有存在的喜欢,更像是field :likes, :int
,这样我就可以得到这样的回复:
{
"data": {
"post" : {
"title" : "Title",
"content" : "This is the content",
"likes" : 7
}
}
}
我的对象应该是什么样子?我想做这样的事情:
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
编辑#1:更具体地说,我想知道如何参数化苦艾对象中的匿名函数。我可以让对象轻松返回非参数化值:
field :somenumber, :integer, resolve: fn (_,_) -> {:ok, 15} end
但是像这样添加一个参数
field :somenumber, :integer, resolve: fn (foo,_) -> {:ok, foo} end
返回以下内容:
...
"somenumber": {},
...
如何传入对象的 id 或隐式关联的查询?
编辑#2:我已经找到了解决方案,但感觉很hacky。
object :post do
field :id, :integer
field :title, :string
field :content, :string
field :likes, :integer, resolve: fn (_,_,resolution) ->
{:ok, Post.getLikeCount(resolution.source.id) }
end
end