1

如果我想要一份周日营业的所有商店的清单,我会

Shop.includes(:opening_times).where("opening_times.day =?", 'Sunday')

有什么办法可以得到周日关门的所有商店的清单吗?也就是说,所有与日栏为“星期日”的记录无关的商店?

我在这里问了这个问题并接受了答案。但是,现在我的数据库变得太大,无法通过首先将所有打开的商店加载到内存中来解决这个问题。有没有办法在不首先获取所有开放商店的数组并将该数组传回数据库的情况下做到这一点?

4

3 回答 3

2

可能有一种更 Railsy 的方式,但只有一个查询(和子查询):

Shop.where("shop_id NOT IN (select opening_times.shop_id from opening_times where opening_times.day = 'Sunday')")

或者,根据链接的问题,您可以使用以下方法进行改进pluck

shop_ids = Shop.includes(:opening_times).where("opening_times.day = ?", 'Sunday').pluck(:id)
shops = Shop.where("id NOT IN(?)", shop_ids)

您正在使用的当前方法 ( map(&:id)) 是为每一行实例化对象,而pluck(:id)将执行select id查询。

于 2013-10-31T23:36:11.533 回答
1

没有更快的方法map是取而代之。

open = Shop.includes(:opening_times).where(opening_times: { day: 'Sunday' }).pluck(:id)
closed = Shop.where.not(id: open)
于 2013-10-31T23:36:29.200 回答
0

我不确定我明白你在问什么,但我会试一试。

当我需要查询没有关联的对象时,我通常会为关联对象的数量创建一个计数器缓存并进行查询。因此,最后,您的查询将如下所示:

Shop.include(:opening_times).where("opening_times.sunday_count", 0)

于 2013-10-31T23:36:18.737 回答