繁体   English   中英

如何基于多个关联模型查询模型

[英]How to query a model based on multiple associated models

我有一个Rails应用程序,其中有以下模型-

城市,酒店,餐厅,公园。

协会是这样的-

class City < ActiveRecord::Base

 has_many :hotels
 has_many :restaurants
 has_many :parks

end

我想查找所有至少拥有一个酒店或餐厅或公园的城市。

如何编写单个查询来获取此类城市?

对于Rails 5,您可以像下面这样使用

cities = City.includes(:hotels, :restaurants, :parks)
cities = ((cities.where.not(hotels: {id: nil})).or(cities.where.not(restaurants: {id: nil})).or(cities.where.not(parks: {id: nil})))

对于较低版本的rails,您需要使用arel_table

城市模型没有有关任何相关信息。 您需要从酒店/公园/等中选择数据。

使用AR的includes查找具有指定关系的所有城市。

City.includes(:hotels, :restaurants, :parks)

最合适的解决方案是使用计数器缓存

然后您应该能够像

City.where('hotels_count > 0 OR restaurants_count > 0 OR parks_count > 0')

PS该查询可以用多种方式.or例如使用.or方法。 此外,如果关联表中有一些数据,请不要忘记重置缓存计数器。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM