Rails:包含 M2M 表时额外不必要的查询

发布于 2024-10-09 08:43:22 字数 364 浏览 0 评论 0原文

假设我有一个教师表,与学生表之间存在 :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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

何时共饮酒 2024-10-16 08:43:22

这是 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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文