Rails:包含 M2M 表时额外不必要的查询
假设我有一个教师表,与学生表之间存在 :has_and_belongs_to_many 关系。我有一个 Students_teachers 表,映射字段 [teacher_id,student_id]。
当我执行查找并希望调出所有教师及其所有学生时,我会执行以下操作:
Teacher.find(:all, :include => :students)
虽然我已包含学生表,但我最终仍然会通过一个查询调出教师,然后再对 Students_teachers 进行 n 个查询表,而 n 是从第一个查询返回的教师数量。
为什么 Rails 尚未加入 Students_teachers 表,而是发送如此多的查询?
Say I've got a Teachers table with a :has_and_belongs_to_many relationship with a Students table. I have a students_teachers table, mapping the fields [teacher_id, student_id].
When I perform a find and wish to bring up all teachers with all their students, I do a:
Teacher.find(:all, :include => :students)
although I've included the students table, I still end up with one query bringing up the teachers, and then n more queries for the students_teachers table, while n is the number of teachers that returned from the first query.
Why doesn't Rails already join on the students_teachers table and instead sends so many queries?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是 Rails 急切加载的预期行为,以防止出现 N+1 问题(即必须运行一个查询来查找所有教师,然后每个教师运行另一个查询来查找所有学生。)请参阅 http://guides.rubyonrails.org/active_record_querying.html#eager-loading-associations。
如果您想在更少的查询中完成此操作,则需要使用
:joins
That's the expected behaviour of Rails' eager loading, to prevent the N+1 problem (i.e. having to run a query to find all the teachers and then another query per teacher to find all their students.) See http://guides.rubyonrails.org/active_record_querying.html#eager-loading-associations.
If you want to do it in fewer queries, you'd need to use
:joins