How to make a MySQL query to return the ordered records on a “joins association” attribute/column?

为君一笑 提交于 2019-12-11 04:25:25

问题


I have models roughly as follows:

class Article < ApplicationRecord
  has_many :writing_associations
  has_many :comments, :through => :writing_associations

  has_many :author_article_associations
  has_many :authors, :through => author_article_associations
end

class Comment < ApplicationRecord
  has_many :writing_associations
  has_many :articles, :through => :writing_associations

  has_many :author_comment_associations
  has_many :authors, :through => :author_comment_associations

  def self.articles_associable_by_author(author)
    author.articles
  end
end

class Author < ApplicationRecord
  has_many :author_article_associations
  has_many :articles, :through => author_article_associations

  has_many :author_comment_associations
  has_many :comments, :through => author_comment_associations
end

class WritingAssociation < ApplicationRecord
  belongs_to :author
  belongs_to :article
  belongs_to :comment
end

class AuthorArticleAssociation < ApplicationRecord
  belongs_to :author
  belongs_to :article
end

class AuthorCommentAssociation < ApplicationRecord
  belongs_to :author
  belongs_to :comment
end

Given a @comment (and an @author with id e.g. equal to 666), I would like to get the articles associated to an author ordered by created_at on the writing_associations of the author.

I tried the following (and many others) without success:

@comment
  .articles_associable_by_author(@author)
  .left_outer_joins(:writing_associations)
  .order('writing_associations.created_at DESC')
  .distinct

The above returns articles associated to the author that are not ordered by created_at on the writing_associations[1]. The related SQL query is:

SELECT 
 DISTINCT 
  `articles`.* 
FROM 
 `articles` 
INNER JOIN 
 `author_article_associations` 
 ON `articles`.`id` = `author_article_associations`.`article_id` 
LEFT OUTER JOIN `writing_associations` 
 ON `writing_associations`.`article_id` = `articles`.`id` 
WHERE `author_article_associations`.`creator_user_id` = 666 
ORDER BY writing_associations.created_at DESC

How can I make the query to return the ordered records?


[1] Furthermore the LEFT OUTER JOINS doesn't care if the writing_associations is associated to the author. I think the JOINS should run something like ... LEFT OUTER JOIN 'writing_associations' ON 'writing_associations'.'article_id' = 'articles'.'id' AND 'writing_associations'.'author_id' = 666 ....

来源:https://stackoverflow.com/questions/54847669/how-to-make-a-mysql-query-to-return-the-ordered-records-on-a-joins-association

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!