counter_cache has_many_through sql优化,减少sql查询次数 [英] counter_cache has_many_through sql optimisation, reduce number of sql queries

查看:8
本文介绍了counter_cache has_many_through sql优化,减少sql查询次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何优化我的 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

最佳解决方案是什么?

这里如何实现 counter_cache ?

And how implement counter_cache here ?

推荐答案

据我所知你不能使用 counter_cachethrough 关联,这就是为什么你应该手动增加它.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆