Rails 3 many to many query condition

前端 未结 3 571
名媛妹妹
名媛妹妹 2021-01-22 20:36

I\'m trying to do a simple Post/Tags relation in rails 3. Everything working fine except when I want to query the Posts which are related to several tags. Basically I\'d like to

3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-22 21:15

    Ok so I found no way to avoid a find_by_sql. Here is what I've done.

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

    I personally don't completely understand this query (found on http://www.sergiy.ca/how-to-write-many-to-many-search-queries-in-mysql-and-hibernate/ - #3). Especially the part where it joins a select. So if anyone could explain how really work this query it would be great.

    Further more, if anyone knows how to do this in a more "rails" way (than a hard coded query), I'd love it.

    Hope this helps some people.

提交回复
热议问题