在 ActiveRecord 中的一个查询中获取多条记录
get multiple records in one query in ActiveRecord
假设我有一只猫 table,每只猫都有独特的颜色。是否有一种 activerecord 方法可用于在一个查询中获取红色和蓝色的猫。我的目标是一个更快的查询,而不是必须使用 Cat.where(color: red) 单独找到每个人然后用蓝色做同样的事情。
你可以这样做:
Cat.where(color: ['red', 'blue'])
这将生成 SQL 查询:
SELECT cats.* FROM cats WHERE cats.color IN ('red', 'blue')
研究JOIN
声明
你也可以在
中使用 OR
where (color='blue' OR color='green')
检查:
Cat.where(color: 'red').or.where(color: 'blue')
或
Cat.where("color = ? OR color = ?", "red", "blue")
或
Cat.where(color: ["red", "blue"])
假设我有一只猫 table,每只猫都有独特的颜色。是否有一种 activerecord 方法可用于在一个查询中获取红色和蓝色的猫。我的目标是一个更快的查询,而不是必须使用 Cat.where(color: red) 单独找到每个人然后用蓝色做同样的事情。
你可以这样做:
Cat.where(color: ['red', 'blue'])
这将生成 SQL 查询:
SELECT cats.* FROM cats WHERE cats.color IN ('red', 'blue')
研究JOIN
声明
你也可以在
中使用OR
where (color='blue' OR color='green')
检查:
Cat.where(color: 'red').or.where(color: 'blue')
或
Cat.where("color = ? OR color = ?", "red", "blue")
或
Cat.where(color: ["red", "blue"])