在这样的Rails中进行查询,通过tag_id查找带有标签的照片预先加载照片上的标签,但只有那些与查询中的tag_ids匹配的标签...当照片稍后被序列化时会曝光...
如何保留所有相关标签,并返回包含这些特定标签的照片?
使用此查询:Photo.includes(:tags).where("tags.id IN (?)", [2, 5, 10).references(:tags)
我想要所有包含标签2,5和10的照片,但如果照片有标签2和3,我希望它在响应中包含标签3.
答案 0 :(得分:0)
可能有更好的方法,但我认为这有效。
# 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})")
答案 1 :(得分:0)
我认为这不能通过单个联接来完成,因为您不能同时将联接表限制为仅具有特定ID的记录,而不能 对其进行限制。
我认为您可以使用Arel做到这一点,但是您将需要2个连接:一个使用where tags.id in (...)
进行限制(您将为其赋予表别名),另一个使用以获得 all 将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])
)
)。>
也许是这样...
class componentA extends React.Component {
constructor(props) {
super(props);
}
render() {
return <View><Text>abc</Text><Button onPress={this.prop.onPress}></Button><View/>;
}
}