counter_cache has_many_through SQL优化,减少SQL查询的数量 [英] counter_cache has_many_through sql optimisation, reduce number of sql queries
问题描述
我如何优化SQL查询,无视这样的情况:
How I can optimise my SQL queries, to ignore situations like this:
Meeting.find(5).users.size => SELECT COUNT(*)FROM ... WHERE ...
Meeting.find(5).users.size => SELECT COUNT(*) FROM ... WHERE ...
User.find(123).meetings.size => SELECT COUNT(*)FROM ... WHERE ...
User.find(123).meetings.size => SELECT COUNT(*) FROm ... WHERE ...
我不知道如何counter_cache在这里使用。
I have no idea how to use counter_cache here.
下面是我的模型关系:
class Meeting < ActiveRecord::Base
has_many :meeting_users
has_many :users, :through => meeting_users
end
class User < ActiveRecord::Base
has_many :meeting_users
has_many :meetings, :through => meeting_users
end
class Meeting_user < ActiveRecord::Base
belongs_to :meeting
belongs_to :user
end
什么是最优化的解决方案?
What are the most optimal solutions ?
和如何在这里实现counter_cache?
And how implement counter_cache here ?
推荐答案
据我知道你无法通过使用 counter_cache
与
的关联,这就是为什么你要手动增加它。
As far as I know you can't use counter_cache
with through
associations, that's why you should manually increment it.
例如(未经测试):
class MeetingUser < ActiveRecord::Base
...
after_create { |record|
Meeting.increment_counter(:users_count, record.meeting.id)
}
after_destroy { |record|
Meeting.decrement_counter(:users_count, record.meeting.id)
}
end
这篇关于counter_cache has_many_through SQL优化,减少SQL查询的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!