2016-08-01 16 views
1

背景:可能編寫一個Ecto查詢來聯合多個表而無需編寫原始SQL?

我正在寫一個簡單的Q/A網站。非常像Stackoverflow,在這個網站中,用戶可以喜歡/ upvote問題,答案或評論。

問:

我很努力寫一個外生的查詢,可以返回所有的問題,答案,或評論,用戶已經喜歡/ upvoted的。

具體來說,我想編寫一個查詢:

  1. 返回所有的問題,意見,並回答由特定用戶upvoted作爲一個單獨的列表
  2. 而有問題,答案的列表,和評論排序時,他們被upvoted

此查詢似乎可能需要UNION,這是從我的理解not yet supported by ecto 2.0

因此,我想知道是否有人可以告訴我或指向我在正確的方向來解決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 

...

schema "answer_upvotes" do 
    belongs_to :answer, Answer 
    belongs_to :user, User 

    timestamps 
end 

...

schema "comment_upvotes" do 
    belongs_to :comment, Comment 
    belongs_to :user, User 

    timestamps 
end 

...

schema "question_upvotes" do 
    belongs_to :question, Question 
    belongs_to :user, User 

    timestamps 
end 

...

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 

...

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 

...

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 

編輯

我可以編寫一個查詢訂購問題,答案,或通過他們的upvoted項目單獨的日期。

例如:

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 

但我不知道如何寫一個,單外生查詢,而無需使用工會或寫原始SQL可以檢索的所有upvoted問題,答案,以及用戶評論。

回答

0

它目前還不支持,但有一個開放的票:https://github.com/elixir-ecto/ecto/issues/1549

+0

感謝您指出我開罰單。我想現在還沒有一種解決方法,除了編寫原始SQL查詢並執行它外,還有其他聯合方法嗎? –

+0

沒錯 - 但如果你這樣做標杆它 - 在很多情況下會更快只是運行單獨的查詢,並++在一起 事情= blah_blah |> Repo.all |>內核++( blah_blah_blah |> Repo.all ) – Mac