Rails scope - 精确匹配的地方
Rails scope - where in exact matches
是否可以使用 where IN (?)
查询在 Rails 中创建范围,这将检查完全匹配?
例如:
Post.joins(:tags).where('tags.id IN (?)', [1, 2, 3, 4])
将找到带有标签 1, 2
、1, 2, 3
和 1, 2, 3, 4
的 post。但是应该只找到带有 1, 2, 3, 4
个标签的 post。
要匹配 IN
子句中的所有值,您必须这样做:
tag_ids = [1, 2, 3, 4]
Post.joins(:tags).where('tags.id IN (?)', tags_ids).group("posts.id")
.having("COUNT(posts.id) >= ?", tag_ids.length)
希望对你有所帮助。
这应该在 pgsql 数据库中工作..
opp_id = Post.joins(:post_tags).group('post.id').having('ARRAY[?] = ARRAY_AGG(post_tags.tag_id ORDER BY post_tags.tag_id)', tags.sort).pluck(:id)
是否可以使用 where IN (?)
查询在 Rails 中创建范围,这将检查完全匹配?
例如:
Post.joins(:tags).where('tags.id IN (?)', [1, 2, 3, 4])
将找到带有标签 1, 2
、1, 2, 3
和 1, 2, 3, 4
的 post。但是应该只找到带有 1, 2, 3, 4
个标签的 post。
要匹配 IN
子句中的所有值,您必须这样做:
tag_ids = [1, 2, 3, 4]
Post.joins(:tags).where('tags.id IN (?)', tags_ids).group("posts.id")
.having("COUNT(posts.id) >= ?", tag_ids.length)
希望对你有所帮助。
这应该在 pgsql 数据库中工作..
opp_id = Post.joins(:post_tags).group('post.id').having('ARRAY[?] = ARRAY_AGG(post_tags.tag_id ORDER BY post_tags.tag_id)', tags.sort).pluck(:id)