gpt4 book ai didi

mysql - 急切加载 Rails 4 - 仍然有多个查询

转载 作者:行者123 更新时间:2023-11-29 02:53:03 24 4
gpt4 key购买 nike

我有这个代码:

class User < ActiveRecord::Base
has_many :people
end

class Person < ActiveRecord::Base
belongs_to :user
end

def map_people people
people.map {|person|
map_person(person)
}
end

def map_person person
{
:person_id => person.id,
:user_id => person.user.id,
:name => person.user.name
}
end

当我运行时:

map_people(Person.with_deleted.includes(:user))

我得到了

 Person Load (1.4ms)  SELECT `people`.* FROM `people`
User Load (2.5ms) SELECT `users`.* FROM `users` WHERE `users`.`deleted_at` IS NULL AND `users`.`id` IN (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 76, 78, 79, 80, 81, 83, 84, 85, 87, 88, 89, 90, 91, 92, 75, 93, 94, 95, 96, 97, 98, 99, 100, 101, 104, 105, 106, 107, 108, 109, 112, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 127, 128, 135, 142, 143) ORDER BY users.updated_at DESC
User Load (0.4ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 1 ORDER BY users.updated_at DESC LIMIT 1
User Load (0.4ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 2 ORDER BY users.updated_at DESC LIMIT 1
User Load (0.5ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 3 ORDER BY users.updated_at DESC LIMIT 1
User Load (0.6ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 3 ORDER BY users.updated_at DESC LIMIT 1
User Load (0.6ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 2 ORDER BY users.updated_at DESC LIMIT 1
User Load (0.6ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 2 ORDER BY users.updated_at DESC LIMIT 1
User Load (0.4ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 1 ORDER BY users.updated_at DESC LIMIT 1

还有更多 SELECT 'users'.* FROM ..... 查询

Hos 可以用一个查询加载所有吗?

谢谢!

大卫

最佳答案

我会尝试使用 eager_load 来做到这一点。这将首先将所有人拉入内存(使用一个查询),然后您可以遍历每个人,每次调用 map_person 方法。

这应该有效:

def map_people
all_people = Person.eager_load(:user).with_deleted.to_a
all_people.map { |person| map_person(person) }
end

如果你愿意,你也可以将 people 数组传递给方法,如下所示:

def map_people(people)
people.map { |person| map_person(person) }
end

all_people = Person.eager_load(:user).with_deleted.to_a
map_people(all_people)

关于mysql - 急切加载 Rails 4 - 仍然有多个查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33632229/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com