简体   繁体   中英

Rails/ActiveRecord: How can I find rows in a table that point to rows in another that match all the specified column values?

I have models named Issue and Label . Each issue can have many labels . Each label can have many issues .

I am trying to build a query that will return an issue that contains all of the supplied labels.

For instance, if I supply ['bug', 'fix', 'enhancement'] I want issues that have all three of those three labels at least.

Currently, I have:

labels = ['bug', 'fix', 'enhancement']
Issue.joins(:labels).where(labels: { name: labels }).distinct

But this is insufficient as it returns issues that have at least one of the label names. I see this is because is because an 'IN' operator is generated:

WHERE "labels"."name" IN ('bug', 'fix', 'enhancement')

And from here on, I'm lost. The labels array can be any length. Can I get the result I want in a single query?

How can I find rows in a table that point to rows in another that match all the specified column values?

我没有检查它,但是也许这种方法可行

Issue.select('issues.id, count(labels.id) as cnt').includes(:labels).where(labels: { name: labels }).group('issues.id').having("cnt = #{labels.size}");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM