这更像是一个“事情为什么会这样”的问题,而不是一个“我不知道怎么做”的问题。
拉关联记录的福音是使用:include因为你会得到一个连接,避免一大堆额外的查询:
Post.all(:include => :comments)
然而,当你查看日志时,没有连接发生:
Post Load (3.7ms) SELECT * FROM "posts"
Comment Load (0.2ms) SELECT "comments.*" FROM "comments"
WHERE ("comments".post_id IN (1,2,3,4))
ORDER BY created_at asc)
它采用了一种捷径,因为它一次拉出了所有的注释,但它仍然不是一个连接(所有文档似乎都是这么说的)。我能得到一个连接的唯一方法是使用:joins而不是:include:
Post.all(:joins => :comments)
日志显示:
Post Load (6.0ms) SELECT "posts".* FROM "posts"
INNER JOIN "comments" ON "posts".id = "comments".post_id
Am I missing something? I have an app with half a dozen associations and on one screen I display data from all of them. Seems like it would be better to have one join-ed query instead of 6 individuals. I know that performance-wise it's not always better to do a join rather than individual queries (in fact if you're going by time spent, it looks like the two individual queries above are faster than the join), but after all the docs I've been reading I'm surprised to see :include not working as advertised.
也许Rails意识到了性能问题,除非在某些情况下才会加入?
'joins'只是用来连接表当你在连接上调用关联时它会再次触发查询(这意味着会触发很多查询)
lets suppose you have tow model, User and Organisation
User has_many organisations
suppose you have 10 organisation for a user
@records= User.joins(:organisations).where("organisations.user_id = 1")
QUERY will be
select * from users INNER JOIN organisations ON organisations.user_id = users.id where organisations.user_id = 1
it will return all records of organisation related to user
and @records.map{|u|u.organisation.name}
it run QUERY like
select * from organisations where organisations.id = x then time(hwo many organisation you have)
在本例中,SQL的总数为11
但随着
'includes'将立即加载所包含的关联并将它们添加到内存中(在第一次加载时加载所有关联),而不会再次触发查询
当你有唱片的时候
@records = User.includes(组织)。(“组织。User_id = 1")
那么query将是
select * from users INNER JOIN organisations ON organisations.user_id = users.id where organisations.user_id = 1
and
select * from organisations where organisations.id IN(IDS of organisation(1, to 10)) if 10 organisation
and when you run this
u @records.map {| | u.organisation.name}
没有查询会触发
博士tl;
我从两个方面对它们进行对比:
joins—用于有条件地选择记录。
includes—在结果集的每个成员上使用关联时。
完整版
join用于过滤来自数据库的结果集。你可以用它在表上做set操作。把它看作是执行集合理论的where子句。
Post.joins(评论)
和
职位。Where ('id in (select post_id from comments)')
除了如果有一个以上的评论,你会得到重复的帖子与连接。但是每个帖子都有评论。你可以用distinct来纠正这个错误:
Post.joins(:comments).count
=> 10
Post.joins(:comments).distinct.count
=> 2
在契约中,includes方法将简单地确保在引用关系时没有额外的数据库查询(这样我们就不会进行n + 1个查询)
Post.includes(:comments).count
=> 4 # includes posts without comments so the count might be higher.
寓意是,当您想要执行条件集操作时使用连接,当您要在集合的每个成员上使用关系时使用包含。