Rails左连接查询,如何创建复杂查询

时间:2015-07-20 12:57:28

标签: ruby-on-rails associations

嘿我试图在rails中创建一个sql查询如何将这个sql查询转换为rails actvie记录。查询是:

   SELECT  f.id, COUNT( f.id  ) AS total               
   FROM    feeds AS f LEFT JOIN feed_likes AS l
    ON f.id = l.feed_id
    GROUP   BY f.id  

有两个表Feed表,另一个是feed_likes。

3 个答案:

答案 0 :(得分:0)

YourClassName.select("feeds.id, feeds.content, count(feed_likes.id) as likes").joins("left join feed_likes on feeds.id = feed_likes.feed_id").group("feeds.id, feeds.content")

你在这里使用ActiveRecord并没有太多收获,你可以直接使用Arel或者只使用find_by_sql()

答案 1 :(得分:0)

帮助

 Feed.joins("LEFT JOIN feed_likes ON feeds.id = feed_likes.feed_id").group("feeds.id").select("feeds.id, feeds.content, COUNT(feed_likes.id) as likes")

匹配查询执行此操作

 Feed.joins("LEFT JOIN feed_likes ON feeds.id = feed_likes.feed_id").group("feeds.id").select("feeds.id, feeds.content, COUNT(feed_likes.id) as likes").to_sql

答案 2 :(得分:0)

要在ActiveRecord中创建此查询,您可以使用每个模型的Arel表为您生成SQL。 假设您有两个ActiveRecord类Feed和FeedLike:

f = Feed.arel_table
fl = FeedLike.arel_table

query = f.join(fl, Arel::Nodes::OuterJoin).on(f[:id].eq(fl[:feed_id]))
         .project(f[:id], f[:id].count.as("Total")) 
         .group(f[:id])

然后,您可以在where子句中使用查询

在查询上调用to_sql将返回以下内容

  

" SELECT \" feeds \"。\" id \",COUNT(\" feeds \"。\&#34 ; id \")AS Total

     

FROM \" feeds \" LEFT OUTER JOIN \" feed_likes \"   ON \" feeds \"。\" id \" = \" feed_likes \"。\" feed_id \

     

GROUP BY \" feeds \"。\" id \""