我对书籍和作家的关系是多对多的,比如:
class Book < ApplicationRecord
has_many :books_authors, inverse_of: :author, dependent: :destroy
has_many :authors, through: :books_authors
end
class Author < ApplicationRecord
has_many :books_authors, dependent: :destroy
has_many :books, through: :books_authors
end
class AuthorsBook < ApplicationRecord
belongs_to :author
belongs_to :book
end
现在要得到所有的
Books
和Authors
的ids: 1 and 3
查询如下:
Book.joins(:authors).where(authors: {id: [1, 3]}).uniq
Book.joins(:books_authors).where(books_authors: {author_id: [1,3]}).uniq
Book.joins(:authors).where('authors.id IN (?)', [1,3]).uniq
但是我得到了一本作者的id是
2,3,5
的书,这不应该是这样,因为它没有带idauthor
的1
。那么,我怎么能只拿到有作者身份证的书呢?
最佳答案
您需要一个having
子句和where子句组合在一起:
ids = [1,3]
Book
.select('books.*') # not sure if this is necessary
.where(authors_books: { author_id: ids })
.joins(:authors_books)
.group('books.id')
.having('count(authors_books) >= ?', ids.size)
SQL:https://www.db-fiddle.com/f/i7TXPJgavLwQCHb4GhgH3b/0
关于sql - Rails过滤多对多关系中的记录,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54260550/