简体   繁体   English

如何以最有效的方式获取所有嵌套记录。 轨道

[英]How to grab all nested records in the most efficient way. Rails

Say a user has many trees and trees have many apples . 假设user有许多treestrees有许多apples Say a method takes in a user's id. 说一种方法接受用户的ID。 I eventually want the data to look something like this: 我最终希望数据看起来像这样:

[
   { tree_id1: [apple1, apple2, apple3] },
   { tree_id2: [apple4, apple5, apple6] },
   { tree_id3: [apple9, apple8, apple7] }
]

So I'll eventually have to iterate through the user's trees and associate the apples with it. 因此,我最终将不得不遍历用户的树并将苹果与之关联。 But I don't want to have to hit the database to retrieve the tree's apples every time. 但是我不想每次都访问数据库来检索树上的苹果。 That seems like it'd be an N+1 (get the user's trees, then all of the tree's apples). 好像是N + 1(先得到用户的树,然后得到所有树的苹果)。

What can I do to retrieve the necessary records efficiently so that I can organize the records in the data format that I need? 我该怎么做才能有效地检索必要的记录,以便可以以所需的数据格式组织记录?

When you make N+1 queries... why is it so bad? 当您进行N + 1个查询时...为什么这么糟糕? Where is the database in relation to app code when you say are on heroku? 当您说在heroku上时,与应用程序代码相关的数据库在哪里? Is it a network call? 是网络电话吗?

You can make use of eager loading 您可以利用急切的加载

users = User.includes(trees: :apples)

Instead of firing N + 1 queries it will fire only three queries 除了触发N + 1个查询,它只会触发三个查询

1) Select * from users
2) Select * from trees where user_id IN [ids_of_users_fetch_from_above_query]
2) Select * from apples where apple_id IN [ids_of_trees_fetch_from_above_query]

So now when you write 所以现在当你写

users.first.apples

No query is fired as the records are already eager loaded when you fetched users 由于在获取用户时已经渴望加载记录,因此不会触发查询

And It is the feature of Rails 这是Rails的功能

You can overcome the N + 1 by applying eager loading 您可以通过应用预先加载来克服N + 1

you can do it by using includes like the blow: 您可以通过使用includes这样的打击做到这一点:

User.includes(trees: :apples)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM