订购和过滤多对多的关系

时间:2012-06-26 20:49:06

标签: mysql ruby-on-rails ruby-on-rails-3

我正在尝试将标记合并到一个网站中,现在已经陷入困境几个小时了。在我的索引页面上,我想显示至少包含当前所有选定标签的所有文章。我看到了Rails 3 many to many query condition并添加了

@articles = Article.find_by_sql([ "SELECT * FROM articles p
JOIN (
    SELECT pt.post_id FROM articles_tags pt
    JOIN posts p ON p.id = pt.articles_id
    JOIN tags t ON t.id = pt.tag_id
    WHERE t.label IN (?)
    GROUP BY pt.post_id
    HAVING count(pt.post_id) = ?
) pt ON p.id = pt.post_id", names_array, names_array.size])

但现在我想要包含创建它的用户并按时间戳排序。 它不会让你通过find_by_sql

的结果包含或排序

帮助

1 个答案:

答案 0 :(得分:0)

假设作者在表'创作者'中,那怎么样:

@articles = Article.find_by_sql([ "SELECT * FROM articles p
JOIN (
    SELECT pt.post_id FROM articles_tags pt
    JOIN posts p ON p.id = pt.articles_id
    JOIN tags t ON t.id = pt.tag_id
    JOIN creators c ON c.id = p.creator_id
    WHERE t.label IN (?)
    GROUP BY pt.post_id
    HAVING count(pt.post_id) = ?
) pt ON p.id = pt.post_id ORDER BY articles.created_at", names_array, names_array.size])