我有这样的查询:
answer_histories = AnswerHistory.where(slide_id: self.slide_id)
.joins(:material_progress).where(material_progresses: {site_id: site.id})
.joins(:learning_history)
.where.not("learning_histories.completed_at":nil)
.where(MaterialProgress.arel_table[:learning_history_id]
.eq(AnswerHistory.arel_table[:learning_history_id]))
此查询执行此代码:
SELECT `answer_histories`.* FROM `answer_histories`
INNER JOIN `material_progresses`
ON `material_progresses`.`id` = `answer_histories`.`material_progress_id`
INNER JOIN `learning_histories`
ON `learning_histories`.`id` = `answer_histories`.`learning_history_id`
AND `learning_histories`.`deleted_at` IS NULL
WHERE `answer_histories`.`deleted_at` IS NULL
AND `answer_histories`.`slide_id` = 809
AND `material_progresses`.`site_id` = 1
但我想这样:
SELECT `answer_histories`.* FROM `answer_histories`
INNER JOIN `material_progresses`
ON `material_progresses`.`id` = `answer_histories`.`material_progress_id`
INNER JOIN `learning_histories`
ON `learning_histories`.`id` = `answer_histories`.`learning_history_id`
AND `learning_histories`.`deleted_at` IS NULL
**AND `learning_histories`.`completed_at` IS NOT NULL**
WHERE `answer_histories`.`deleted_at` IS NULL
AND `answer_histories`.`slide_id` = 809
AND `material_progresses`.`site_id` = 1
如何更改上述查询?
答案 0 :(得分:0)
我会做类似的事情:
class LearningHistory < ApplicationRecord
...
scope :completed, ->{ where.not(completed_at: nil) }
然后:
answer_histories = AnswerHistory.where(slide_id: self.slide_id)
.joins(:material_progress).where(material_progresses: {site_id: site.id})
.joins(:learning_history)
.merge(LearningHistory.completed)
.where(MaterialProgress.arel_table[:learning_history_id]
.eq(AnswerHistory.arel_table[:learning_history_id]))