2

我正在运行这个 ActiveRecord 语句

@items = Item.joins(:order => :person)
             .select('items.*').select('orders.*')
             .includes(:order => [:person, :organization])
             .order('created_at DESC')
             .limit(10)

这些是查询:

SELECT items.*, orders.* FROM items INNER JOIN orders ON orders.id = items.order_id INNER JOIN people ON  people.id = orders.person_id WHERE items.deleted_at IS NULL ORDER BY created_at DESC LIMIT 10
Item Load (0.001ms) 

SELECT (trace)
SELECT orders.* FROM orders WHERE orders.deleted_at IS NULL AND orders.id IN (51, 50, 49, 48, 47, 46) ORDER BY orders.created_at DESC
Order Load (0.000ms) 

SELECT (trace)
SELECT people.* FROM people WHERE people.deleted_at IS NULL AND people.id IN (11, 22, 21, 19, 18)
Person Load (0.000ms)  

SELECT (trace)
SELECT organizations.* FROM organizations WHERE organizations.id IN (1)
Organization Load (0.000ms)  

SELECT items.*, orders.*如果 ActiveRecord 在第一个查询中已经使用 INNER JOIN 进行了选择,为什么还要从数据库中重新选择数据?如何在不返回数据库的情况下让它为 item.order 补水?

4

1 回答 1

0

嗨,当使用 ActiveRecord 连接时,它总是在您的关系模型之间找到匹配的数据。

示例:如果 Person 有很多 Items 并且 Items 属于 Person,则 activerecord 查询将是:

Item.find(:all, :joins => :person, :select => "items.name, persons.full_name", :conditions => ["persons.full_name = ?", 'Allen', :order => "persons.created_at DESC"])

上面的代码返回所有项目名称和人的全名,其中全名 = 'Allen' 和订单到 created_at DESC 或persons 表。因此,当 Person 的 id 等于 Item 的 person_id 列时,您的日志中会有很多 INNER JOIN 查询。

于 2013-05-04T16:06:05.047 回答