在Rails中执行这样的查询,以通过tag_id查找带有标签的照片,将标签预加载到照片上,但只有那些与查询中的tag_ids匹配的标签...这会在以后序列化照片时暴露出来。
如何保留所有关联的标签,并返回具有这些特定标签的照片?
使用以下查询:Photo.includes(:tags).where("tags.id IN (?)", [2, 5, 10).references(:tags)
我想要所有有标签2、5和10的照片,但如果一张照片有标签2和3,我希望它在响应中包括标签3。
发布于 2016-06-07 23:31:10
也许有一种更好的方法,但我认为这是可行的。
# Build a query for all photo IDs that have the specified tags.
photo_ids_query = Photo.joins(:tags)
.where(:tags => { :id => [2, 5, 10] })
.select("photos.id")
# Load that list of photo IDs using a subquery.
Photo.includes(:tags)
.where("photos.id IN (#{photo_ids_query.to_sql})")发布于 2020-01-18 04:05:12
我不认为使用单个连接就能做到这一点,因为您不能同时将连接表限制为仅具有特定it的那些记录,而不限制它。
我认为你可以用Arel做到这一点,但你需要两个连接:一个用where tags.id in (...)限制(你给它一个表别名),一个让所有的Tag连接到返回的每个Photo(默认连接,这样它就是关联方法使用的连接,比如photo.tags)。
也许就像这样..。
photos = Photo.arel_table
restricted_tags = Tag.arel_table.alias(:restricted_tags)
Photo.
includes(:tags).
joins(
photos.join(restricted_tags).on(
tags[:photo_id].eq(photos[:id]) # or whatever your join conditions are in your particular case
).join_sources
).where(
restricted_tags.in([2, 5, 10])
)https://stackoverflow.com/questions/37669693
复制相似问题