gpt4 book ai didi

ruby-on-rails - 在 ActiveRecord 中查询包含来自多个数组的一个或多个 id 的对象

转载 作者:行者123 更新时间:2023-12-04 14:03:59 26 4
gpt4 key购买 nike

我有包含三个模型的 Rails 5.2 项目:

class Post
has_many :post_tags
has_many :tags, through: :post_tags
end

class PostTags
belongs_to :post
belongs_to :tag
end

class Tags
has_many :post_tags
has_many :posts, through: :post_tags
end
我有许多标签 ID 数组,例如:
array_1 = [3, 4, 5]
array_2 = [5, 6, 8]
array_3 = [9, 11, 13]
我想要一个查询,该查询将返回标有至少一个带有来自每个数组的 id 的标签的帖子。
例如,假设我有一个带有以下标签 ID 的帖子:
> post = Post.find(1)
> post.tag_ids
> [4, 8]
如果我使用 array_1 运行查询和 array_2它会返回这个帖子。但是,如果我用 array_1 运行它, array_2array_3它不会返回这篇文章。
我尝试使用以下查询进行此操作:
Post.joins(:tags).where('tags.id IN (?) AND tags.id IN (?)', array_1, array_2)
但这不会返回帖子。
返回帖子的查询应该是什么?
任何帮助将不胜感激!

最佳答案

由于您已使用 postgresql 标记了此问题,因此您可以使用 intersect 执行您想要的查询。关键词。不幸的是,activerecord 本身并不支持 intersect所以你必须构建 sql 才能使用这种方法。

array_1 = [3, 4, 5]
array_2 = [5, 6, 8]

query = [array_1, array_2].map do |tag_ids|
Post.joins(:tags).where(tags: { id: tag_ids }).to_sql
end.join(' intersect ')

Post.find_by_sql(query)
编辑 :
我们可以使用子查询来返回帖子并维护 activerecord 关系。
array_1 = [3, 4, 5]
array_2 = [5, 6, 8]

Post
.where(post_tags: PostTag.where(tag_id: array_1))
.where(post_tags: PostTag.where(tag_id: array_2))
如需加分,您可以转 where(post_tag: PostTag.where(tag_id: array_1))进入 Posts 的范围并根据需要将它们链接起来。

关于ruby-on-rails - 在 ActiveRecord 中查询包含来自多个数组的一个或多个 id 的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69107021/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com