我正在运行此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)
如果ActiveRecord在第一个SELECT items.*, orders.*
查询中使用INNER JOIN已经SELECT了,那么为什么ActiveRecord会重新选择数据库中的数据?如何在没有返回数据库的情况下将它保存为item.order?
答案 0 :(得分: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或人员表。所以当Person的id等于Item的person_id列时,你的日志中会有很多INNER JOIN查询。