sql - 将 SQL 查询转换为具有多对多关系的 Rails 查询,最佳实践是什么?
问题描述
嗨,这是我的数据模型:
我想将此查询转换为 activeRecord API
select c.id, c.name, c.phone, c.created_at,c.updated_at,s.status
from contacts c,contacts_lists cl, contactstatuses s
where cl.list_id = ? and s.company_id = ? and c.id = cl.contact_id and c.id = s.contact_id
最好的方法是什么?....这里的最佳做法是什么?,运行 sql plain 或使用 activeRecord API
解决方案
您可以使用连接将您需要的所有表连接在一起。我假设你已经在你的模型中设置了所有的关系并且你的模型被命名为 Contact、Contactstatus 和 ContactList。然后你应该能够构建一个像这样的查询:
select c.id, c.name, c.phone, c.created_at, c.updated_at, s.status
from contacts c
JOINS contacts_lists cl ON cl.contact_id = c.id
JOINS contactstatuses s ON s.contact_id = c.id
where cl.list_id = ?
and s.company_id = ?;
使用以下代码:
# I filled the id values (questionmarks) with a 1
Contact.select(:id, :name, :phone, :created_at, :updated_at, Contactstatus.arel_table[:status]).joins(:contacts_lists, :contactstatuses).where(contacts_lists: { list_id: 1 }, contactstatuses: { company_id: 1 })
推荐阅读
- netflix-eureka - 如何配置备用 SSL 属性以连接到 Spring Boot Admin?
- visual-studio-code - 如何在树莓派上安装 VSCode
- javascript - 对文本有更多控制的 TextArea 的替代品?
- c# - Excel 12.0 Interop 使用 C# 在 Excel 2016 上随机运行
- hadoop2 - 我们可以在现有集群中将 ambari 配置为非 root 用户吗
- javascript - 当我在 IE 浏览器中检查元素时,角度计时器起作用
- python - 如何通过 qcut 获取 bin 值
- javascript - 动态 HTML 显示当前日期
- python - 为什么 python 脚本不能打印到控制台或不能在 Ubuntu 中使用 pdb 进行调试
- oop - 什么时候使用casting/instanceof好?