我有两个型号
class Activity
has_and_belongs_to_many :photos, -> { where "deleted = false"}
end
class Photo
has_and_belongs_to_many :activities
end
我们假设我只有1个活动,它有2张照片
当我尝试加载活动列表并急切加载相应的照片时,每项活动仅返回1张照片
activities = Activity.all.includes(:photos)
a.first.id # => 1
a.first.photos.size # => 1
运行的相应SQL查询是
SELECT `activities`.* FROM `activities`
SELECT `activities_photos`.*, `activities_photos`.`activity_id` AS t0_r0, `activities_photos`.`photo_id` AS t0_r1, `photos`.`id` AS t1_r0, `photos`.`primary_photo` AS t1_r1, `photos`.`created_at` AS t1_r2, `photos`.`updated_at` AS t1_r3, `photos`.`deleted` AS t1_r4, `photos`.`url` AS t1_r5, `photos`.`thumbnail_url` AS t1_r6 FROM `activities_photos` LEFT OUTER JOIN `photos` ON `photos`.`id` = `activities_photos`.`photo_id` WHERE (deleted = false) AND `activities_photos`.`activity_id` IN (1)
当我在MYSQL中运行时,第二个查询返回2行。
Wierd对吗?
这是它变得更加危险的地方
我不急于加载照片'但是为每个活动单独加载
activities = Activity.all
a.first.id # => 1
a.first.photos.size # => 2
所以这次我得到了所有必需的数据。
运行的相应SQL查询是
SELECT `activities`.* FROM `activities`
SELECT `photos`.* FROM `photos` INNER JOIN `activities_photos` ON `photos`.`id` = `activities_photos`.`photo_id` WHERE `activities_photos`.`activity_id` = ? AND (deleted = false) [["activity_id", 1]]
如何通过热切的加载来获取所有照片。
我做错了什么或是一些奇怪的错误?