Jos*_*uve 2 elixir ecto phoenix-framework
背景:
我正在写一个简单的问答网站。与 Stackoverflow 非常相似,在此站点中,用户可以对问题、答案或评论点赞/投票。
问题:
我正在努力编写一个 Ecto 查询,它可以返回用户喜欢/点赞的所有问题、答案或评论。
具体来说,我想编写一个查询:
这个查询似乎可能需要 UNION,据我了解ecto 2.0 尚不支持 UNION。
因此,我想知道是否有人可以向我展示或指出在 Ecto 中解决此类查询的正确方向。感谢您的任何帮助。
以下是相关模型的架构。
...
schema "users" do
...
has_many :answer_upvotes, AnswerUpvote
has_many :comment_upvotes, CommentUpvote
has_many :question_upvotes, QuestionUpvote
many_to_many :upvoted_answers, Answer, join_through: AnswerUpvote
many_to_many :upvoted_comments, Comment, join_through: CommentUpvote
many_to_many :upvoted_questions, Question, join_through: QuestionUpvote
timestamps
end
Run Code Online (Sandbox Code Playgroud)
...
schema "answer_upvotes" do
belongs_to :answer, Answer
belongs_to :user, User
timestamps
end
Run Code Online (Sandbox Code Playgroud)
...
schema "comment_upvotes" do
belongs_to :comment, Comment
belongs_to :user, User
timestamps
end
Run Code Online (Sandbox Code Playgroud)
...
schema "question_upvotes" do
belongs_to :question, Question
belongs_to :user, User
timestamps
end
Run Code Online (Sandbox Code Playgroud)
...
schema "questions" do
...
belongs_to :user, User
has_many :answers, Answer
has_many :upvotes, QuestionUpvote
many_to_many :upvoting_users, User, join_through: QuestionUpvote
timestamps
end
Run Code Online (Sandbox Code Playgroud)
...
schema "answers" do
...
belongs_to :question, Question
belongs_to :user, User
has_many :comments, Comment
has_many :upvotes, AnswerUpvote
many_to_many :upvoting_users, User, join_through: AnswerUpvote
timestamps
end
Run Code Online (Sandbox Code Playgroud)
...
schema "comments" do
...
belongs_to :answer, Answer
belongs_to :user, User
has_many :upvotes, CommentUpvote
many_to_many :upvoting_users, User, join_through: CommentUpvote
timestamps
end
Run Code Online (Sandbox Code Playgroud)
编辑
我可以编写一个查询来按问题、答案或项目的投票日期单独排序。
例如:
upvoted_answers_query =
from answer in Answer,
join: upvote in assoc(answer, :upvotes), where: upvote.user_id == ^user.id,
order_by: upvote.inserted_at
select: answer
Run Code Online (Sandbox Code Playgroud)
但我不确定如何编写一个单一的 Ecto 查询,该查询可以检索用户所有投票的问题、答案和评论,而无需使用联合或编写原始 SQL。
Ecto v3.0.0 (2018-10-29) 添加了对union和的支持union_all。
文档中的示例:
supplier_query = from s in Supplier, select: s.city
from c in Customer, select: c.city, union: ^supplier_query
Run Code Online (Sandbox Code Playgroud)
https://hexdocs.pm/ecto/Ecto.Query.html#union/2