Multiple table joins in rails(Rails 中的多个表连接)
问题描述
如何将下面的 mysql 查询写入 rails activerecord
How do I write the mysql query below into rails activerecord
我知道如何在两个表上编写连接;但是,我对如何在 3 个表上使用连接不是很有信心.
I know how to write joins on two tables; however, I'm not very confident on how to use join on 3 tables.
推荐答案
要重写您的问题中的 SQL 查询,我认为它应该如下所示(尽管我很难完全可视化您的模型关系,所以这有点猜测):
To rewrite the SQL query you've got in your question, I think it should be like the following (though I'm having a hard time fully visualizing your model relationships, so this is a bit of guesswork):
...这样 joins
方法处理两个连接以及 WHERE
子句,最后是 group调用.
...such that the joins
method takes care of both of the two joins as well as the WHERE
clause, followed finally by the group
call.
更多供参考:
如果您将多个关联加入同一模型您可以简单地列出它们:
If you're joining multiple associations to the same model you can simply list them:
如果您要加入嵌套表,您可以将它们以散列形式列出:
If you're joining nested tables you can list them as in a hash:
嵌套关联,多级:
您还可以链接 ActiveRecord 查询接口调用,例如:
You can also chain ActiveRecord Query Interface calls such that:
如果所有其他方法都失败了,您可以随时直接传递 SQL 片段进入 joins
方法 作为从你的工作查询到更以 ARQI 为中心的东西的垫脚石
If all else fails you can always pass a SQL fragment directly into the joins
method as a stepping stone to getting from your working query to something more ARQI-centric
这篇关于Rails 中的多个表连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!