mysql - 从多个嵌套记录加载记录的复杂查询

标签 mysql ruby-on-rails activerecord

我有一个用户模型

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/

相关文章:

mysql - SQL Server 2008 R2 到 MySQL 迁移

ruby-on-rails - 如何检查 ActiveRecord::Base 对象上存在的验证

mysql - 存储平均正常运行时间数据的最佳方法

mysql - 从原始数据文件恢复 MySQL 数据库 [XAMPP | MySQL |数据库]

使用之间的Mysql查询问题

javascript - 将 Javascript 格式化为 CoffeeScript

ruby-on-rails - Ruby on Rails : Is there a method to retrieve an array of data from the database without Rails needing to instantiate anything?

javascript - rails : has_many association through array of object IDs from form

MySQL删除仅存在于子表/cakephp更新中的记录?

ruby-on-rails - Rails如何使用mail_form?