简体   繁体   English

将复杂的SQL查询转换为Rails ActiveRecord表达式

[英]Converting complicated SQL query into Rails ActiveRecord expression

I have the following SQL which I cannot seem to express using active record objects/methods in Rails. 我有以下SQL,我似乎无法在Rails中使用活动记录对象/方法来表达。

SELECT users.*, count(followings.user_id) as expr1 FROM users 
  inner join followings on id = follows where id in (2,3,4) 
  group by followings.follows order by expr1 desc;

Obviously, [2,3,4] is replaced with any array of Ids. 显然,[2,3,4]被替换为任何Ids数组。

This query executes no problems, and gives the results I want. 该查询不执行任何问题,并给出我想要的结果。 But I am having great difficulty in how to go about expressing it the 'ActiveRecord' way. 但是我在如何以“ ActiveRecord”方式表达方面遇到很大困难。

How do I get my Users model to order by the number followers? 如何按数字关注者订购用户模型?

You can try with this query: 您可以尝试使用以下查询:

User.select("users.*, count(followings.user_id)").joins(:followings)
.where("users.in (?)", [2,3,4]).group_by("followings.follows")

If you are getting other errors please let me know. 如果您遇到其他错误,请告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM