简体   繁体   中英

Mongoid: Return documents related to relation?

Say I'm modeling Students, Lessons, and Teachers. Given a single student enrolled in many lessons, how would I find all of their teachers of classes that are level 102? For that matter, how would I find all of their lessons' teachers? Right now, I have this:

s = Mongoid::Student.find_by(name: 'Billy')
l = s.lessons.where(level: 102)
t = l.map { |lesson| lesson.teachers }.flatten

Is there a way to do turn the second two lines into one query?

Each collection requires at least one query, there's no way to access more than one collection in one query (ie no JOINs) so that's the best you can do. However, this:

t = l.map { |lesson| lesson.teachers }.flatten

is doing l.length queries to get the teachers per lesson. You can clean that up by collecting all the teacher IDs from the lessons:

teacher_ids = l.map(&:teacher_ids).flatten.uniq # Or use `inject` or ...

and then grab the teachers based on those IDs:

t = Teacher.find(teacher_ids)
# or
t = Teacher.where(:id.in => teacher_ids).to_a

If all those queries don't work for you then you're stuck with denormalizing something so that you have everything you need embedded in a single collection; this would of course mean that you'd have to maintain the copies as things change and periodically sanity check the copies for consistency problems.

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