如何在 Rails 中编写复杂的 Active Record 查询
How to Write Complex Active Record Query in Rails
我需要一个活动记录查询来获取一个数组。模型的 CRUDS 工作正常,但我需要在视图文件中获取数组。我有以下 SQL 语法。
select FirstName from Person.Person
LEFT JOIN Sales.SalesPerson
ON Person.BusinessEntityID = SalesPerson.BusinessEntityID
LEFT JOIN Sales.SalesTerritory
ON SalesPerson.TerritoryID = SalesTerritory.TerritoryID
where SalesPerson.BusinessEntityID is null and SalesPerson.TerritoryID is null
rails 中的 Active Record 查询语法是什么?有什么想法吗?
除了大小写和表名外,您的查询应如下所示
Person.left_joins(:sales_person, :sales_territory).
where(sales_persons: {business_entity_id: nil, territory_id: nil}).
pluck(:first_name)
接受的答案将生成如下错误查询
select * from persons
left outer join sales_persons on sales_persons.person_id = persons.id
left outer join sales_territories on sales_territories.person_id = persons.id
SalesTerritory table 加入了 Person 但根据您的 SQL 它应该加入 SalesPerson
因为它是一个嵌套连接,所以下面将生成正确的 SQL
Person.select(:first_name).left_joins(sales_person: :sales_territory).
where(sales_persons: {business_entity_id: nil, territory_id: nil}).
pluck(:first_name)
我需要一个活动记录查询来获取一个数组。模型的 CRUDS 工作正常,但我需要在视图文件中获取数组。我有以下 SQL 语法。
select FirstName from Person.Person
LEFT JOIN Sales.SalesPerson
ON Person.BusinessEntityID = SalesPerson.BusinessEntityID
LEFT JOIN Sales.SalesTerritory
ON SalesPerson.TerritoryID = SalesTerritory.TerritoryID
where SalesPerson.BusinessEntityID is null and SalesPerson.TerritoryID is null
rails 中的 Active Record 查询语法是什么?有什么想法吗?
除了大小写和表名外,您的查询应如下所示
Person.left_joins(:sales_person, :sales_territory).
where(sales_persons: {business_entity_id: nil, territory_id: nil}).
pluck(:first_name)
接受的答案将生成如下错误查询
select * from persons
left outer join sales_persons on sales_persons.person_id = persons.id
left outer join sales_territories on sales_territories.person_id = persons.id
SalesTerritory table 加入了 Person 但根据您的 SQL 它应该加入 SalesPerson
因为它是一个嵌套连接,所以下面将生成正确的 SQL
Person.select(:first_name).left_joins(sales_person: :sales_territory).
where(sales_persons: {business_entity_id: nil, territory_id: nil}).
pluck(:first_name)