Rails 过滤多对多关系的记录
Rails filtering records in many to many relationship
我与书籍和作者之间存在多对多关系,例如:
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
现在获取 ids: 1 and 3
中 Authors
的所有 Books
查询类似于:
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
,但情况并非如此,因为它没有 author
和 ID 1
。
那么,我怎样才能只获得具有给定作者 ID 的书籍?
您需要一个 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)
我与书籍和作者之间存在多对多关系,例如:
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
现在获取 ids: 1 and 3
中 Authors
的所有 Books
查询类似于:
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
,但情况并非如此,因为它没有 author
和 ID 1
。
那么,我怎样才能只获得具有给定作者 ID 的书籍?
您需要一个 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)