ActiveRecord 在一次查询中查找关联记录的关联记录
ActiveRecord find associated records of associated records in one query
我正在尝试找到一种 ActiveRecord and/or SQL 方法来仅对以下内容使用 1 个查询
获取作者所写的所有章节,前提是一位作者 has_many 本书和一本书 has_many 章节
class Author < ActiveRecord::Base
has_many :books
end
class Book < ActiveRecord::Base
belongs_to :author
has_many :chapters
end
class Chapter < ActiveRecord::Base
belongs_to :book
end
这有效,但它使用两个查询
Chapter.where(book_id: author.books.map(&:id))
Book Load (0.4ms) SELECT `books`.* FROM `books` WHERE `books`.`author_id` = 1
Chapter Load (0.4ms) SELECT `chapters`.* FROM `chapters` WHERE `chapters`.`book_id` IN (1, 2, 3)
这有效,但它returns 是一个数组对象而不是 ActiveRecord 关系对象
author.books.map(&:chapters)
通过关联使用has_many:
class Author < ActiveRecord::Base
has_many :books
has_many :chapters, through: :books
end
然后像这样使用它:
author = Author.find(...)
author.chapters
我正在尝试找到一种 ActiveRecord and/or SQL 方法来仅对以下内容使用 1 个查询
获取作者所写的所有章节,前提是一位作者 has_many 本书和一本书 has_many 章节
class Author < ActiveRecord::Base
has_many :books
end
class Book < ActiveRecord::Base
belongs_to :author
has_many :chapters
end
class Chapter < ActiveRecord::Base
belongs_to :book
end
这有效,但它使用两个查询
Chapter.where(book_id: author.books.map(&:id))
Book Load (0.4ms) SELECT `books`.* FROM `books` WHERE `books`.`author_id` = 1
Chapter Load (0.4ms) SELECT `chapters`.* FROM `chapters` WHERE `chapters`.`book_id` IN (1, 2, 3)
这有效,但它returns 是一个数组对象而不是 ActiveRecord 关系对象
author.books.map(&:chapters)
通过关联使用has_many:
class Author < ActiveRecord::Base
has_many :books
has_many :chapters, through: :books
end
然后像这样使用它:
author = Author.find(...)
author.chapters