我有三个名为test_templates,sections和questions的表。每个test_templates包含一些部分,每个部分可能有多个问题。现在我想显示问题计数。还有三种类型的问题
每种类型的个人计数。我尝试了下面的代码,但它给了我完整的计数,不是每个类型单独
foreach ($args['listing'] as $value) {
$args['sections'][$value->id] = Section::leftJoin('questions','sections.id','=','questions.section_id')
->select('sections.template_id','sections.section_name','questions.question_type_id',
DB::raw("(CASE WHEN (questions.question_type_id = 1) THEN count(questions.id) END) as count_1"),DB::raw("(CASE WHEN (questions.question_type_id = 2) THEN count(questions.id) END) as count_2"),DB::raw("(CASE WHEN (questions.question_type_id = 3) THEN count(questions.id) END) as count_3"))
->where('sections.template_id','=',$value->id)
->groupBy('sections.id')
->get();
}
答案 0 :(得分:0)
最后,我整理了上述问题,例如:
来自这些表的数据以及代表特定类型的计数可在同一查询中找到
foreach ($args['listing'] as $value) { $args['sections'][$value->id] = Section::leftJoin('questions','sections.id','=','questions.section_id') ->select('sections.*','questions.question_type_id' ,DB::raw('(SELECT count(questions.id) FROM `questions` WHERE `question_type_id` = 1) as mulitple_questions') ,DB::raw('(SELECT count(questions.id) FROM `questions` WHERE `question_type_id` = 2) as coding_questions') ,DB::raw('(SELECT count(questions.id) FROM `questions` WHERE `question_type_id` = 3) as submission_questions')) ->where('sections.template_id','=',$value->id) ->groupBy('sections.id') ->get(); }