我有一个用户模型
class User < ActiveRecord::Base
has_many :watched_videos
has_and_belongs_to :course
end
和类(class)模型
class Course < ActiveRecord::Base
has_many :videos
has_and_belongs_to :users
end
和视频模型
class Video < ActiveRecord::Base
belongs_to :course
has_many :watched_videos
end
我的视频模型看起来像
class WatchedVideo < ActiveRecord::Base
belongs_to :user
belongs_to :video
end
我想要所有视频已被用户观看过的所有类(class)。例如。有两门类(class),每门类(class)有 2 个视频,用户已经观看了类(class)一的所有视频,我的查询必须返回该类(class)。我该如何实现这个?
最佳答案
首先获取所有观看过任何视频的用户:
users = WatchedVideo.pluck('Distinct("user_id")')
获取具有以上用户的所有类(class):
courses = Course.includes(:videos).where('user_id in (?)', users)
迭代类(class)以查找观看了所有视频的类(class):
cour = []
courses.each do |c|
c.users.each do |u|
cour << c if u.wathced_videos.pluck(:video_id) == c.videos.pluck(:id)
end
end
还有优化的余地。您可以进一步优化它
关于mysql - 从多个嵌套记录加载记录的复杂查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27739365/