简体   繁体   English

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

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

I have a rails application where I have following models - 我有一个Rails应用程序,其中有以下模型-

City, Hotel, Restaurant, Park. 城市,酒店,餐厅,公园。

Associations are like this - 协会是这样的-

class City < ActiveRecord::Base

 has_many :hotels
 has_many :restaurants
 has_many :parks

end

I want to find all cities that have at least one hotel or restaurant or Park. 我想查找所有至少拥有一个酒店或餐厅或公园的城市。

How do I write single query to fetch such cities ? 如何编写单个查询来获取此类城市?

For Rails 5, you can use like below 对于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})))

For lower version of rails , you need to use arel_table 对于较低版本的rails,您需要使用arel_table

The City model doesn't have any information about related stuff. 城市模型没有有关任何相关信息。 You need to select the data from hotel/park/etc. 您需要从酒店/公园/等中选择数据。

Use AR's includes to find the all Cities with specified relations. 使用AR的includes查找具有指定关系的所有城市。

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

Most appropriate solution would be using counter cache 最合适的解决方案是使用计数器缓存

Then you should be able to query like 然后您应该能够像

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

PS This query can be re-written many ways eg use .or method. PS该查询可以用多种方式.or例如使用.or方法。 Also, don't forget to reset cache counter if you have some data in associated tables. 此外,如果关联表中有一些数据,请不要忘记重置缓存计数器。

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

相关问题 Rails基于缺少条件的关联模型来查询一个模型 - Rails query one model based on the lack of an associated model with conditions 如何基于基于与行关联的其他表中的多个行的值进行查询 - How to query based on values based on multiple rows in other table associated with row Rails 5:如何通过关联的模型属性对模型进行排序,并使其与众不同 - Rails 5: How to order models by associated model attribute, and make them distinct 雄辩地获得与模型X相关的所有模型 - Eloquent get all models associated with model X 如何根据关联模型中的字段查找模型 - How to find models depending on fields in associated models 如何通过带有条件的关联模型字段对查询结果进行排序? - How do I order query results by an associated model field with conditions? 根据关联模型的条件在模型中查找记录 - find records in model based on conditions of associated model 如何根据关联模型的值过滤分页结果? (CakePHP 2.x) - How can I filter paginated results based on the value of associated models? (CakePHP 2.x) 一个模型如何具有多个具有与值相同类型的模型的键? - How can a model have multiple keys with the same type of models as values? 如何获得至少具有多个“ hasmany”模型的N个相关性的随机模型 - How to get a random model with at least N related of multiple `hasmany` models
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM