我有一种情况,学校和 EventLeg 记录通过属于给定事件的照片绑定在一起。
class Photo < ActiveRecord::Base
belongs_to :event
belongs_to :event_leg
has_and_belongs_to_many :schools
end
class Event < ActiveRecord::Base
has_many :event_legs, :through => :photos, :group => 'event_legs.id'
has_many :photos
end
class School < ActiveRecord::Base
has_and_belongs_to_many :photos
has_many :events, :through => :photos
has_many :event_legs, :through => :photos
end
class EventLeg < ActiveRecord::Base
has_many :photos
has_many :schools, :through => :photos
end
我需要在某个事件中获取出现在给定事件段中的学校。
@event = Event.find 4088
@event.schools.joins(:photos).where('photos.event_leg_id' => 28034)
这导致 SQL 将photos_schools
表连接两次,一次 toschools
和一次 to photos
:
SELECT DISTINCT `schools`.* FROM `schools`
INNER JOIN `photos_schools` `photos_schools_join` ON `photos_schools_join`.`school_id` = `schools`.`id`
INNER JOIN `photos` `photos_schools_2` ON `photos_schools_2`.`id` = `photos_schools_join`.`photo_id`
INNER JOIN `photos_schools` ON `schools`.`id` = `photos_schools`.`school_id`
INNER JOIN `photos` ON `photos_schools`.`photo_id` = `photos`.`id`
WHERE `photos`.`event_id` = 4088 AND `photos`.`event_leg_id` = 28034
photos_schools -> photos 的第二个 JOIN 是不必要的,下面的查询做同样的事情而且速度更快:
SELECT DISTINCT `schools`.* FROM `schools`
INNER JOIN `photos_schools` ON `schools`.`id` = `photos_schools`.`school_id`
INNER JOIN `photos` ON `photos_schools`.`photo_id` = `photos`.`id`
WHERE `photos`.`event_id` = 4088 AND photos.event_leg_id = 28034;
那么为什么 AR 会创建第二组连接,我怎样才能让它停止呢?