使用Laravel将行数据转换为列数据

时间:2018-05-20 05:03:14

标签: php laravel

您好我遇到了问题。我正尽力解决这个问题,但不能。我正在尝试这样做I have three table which is illustrated below image. I want to Output like last table in the given image

这是我的laravel代码------------------

$academic_year=$request->academic_year;
        $class=$request->class_name;
        $medium=$request->medium;
        $section=$request->section_name;        
        $exam_name=$request->exam_name;

        $subject_list=DB::table('tbl_subject')                    
                    ->where('class_name', 'LIKE', "%$class%")                                       
                    ->get();     


$student_all_subject_mark_search_result=DB::table('tbl_student_subject_mark') 
            ->join('tbl_student_admission', 'tbl_student_subject_mark.student_registration_id', '=', 'tbl_student_admission.student_registration_id')
            ->select('tbl_student_subject_mark.*', 'tbl_student_admission.student_registration_id',  'tbl_student_admission.student_full_name_english', 'tbl_student_admission.class', 'tbl_student_admission.medium', 'tbl_student_admission.section', 'tbl_student_admission.roll_no',
            'max(if(subject_name = "Bangla 1st Paper" , total_obtained_mark, null)) A',
            'max(if(subject_name = "Bangla 2nd Paper" , total_obtained_mark, null)) B',
            'max(if(subject_name = "English 1st Paper" , total_obtained_mark, null)) C',
            'max(if(subject_name = "English 2nd Paper" , total_obtained_mark, null)) D',
            'max(if(subject_name = "Mathematics" , total_obtained_mark, null)) E',
            'max(if(subject_name = "Religion" , total_obtained_mark, null)) F')
            ->where('tbl_student_subject_mark.academic_year', $academic_year)
            ->where('tbl_student_admission.class', $class)
            ->where('tbl_student_admission.medium', $medium)
            ->where('tbl_student_admission.section', $section)                
            ->where('tbl_student_subject_mark.exam_title', $exam_name)
            ->where('tbl_student_admission.student_registration_id is not null')
            ->groupBy('tbl_student_subject_mark.student_registration_id')                
            ->get();

但它显示错误

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'max(if(subject_name 
= "Bangla 1st Paper" , total_obtained_mark, null)) A' in 'field list' (SQL: 
select `tbl_student_subject_mark`.*, 
`tbl_student_admission`.`student_registration_id`, ..................

1 个答案:

答案 0 :(得分:0)

您可能需要使用selectRaw()而非正常选择,因为您要传递自定义查询条件:

所以你有一个字符串:

->selectRaw('tbl_student_subject_mark.*, tbl_student_admission.student_registration_id.....,
    max(if(subject_name = "Bangla 1st Paper" , total_obtained_mark, null)) A....')
->where('tbl_student_subject_mark.academic_year', $academic_year)
....
  

请注意起始和结束引用' '

详细了解“查询构建器here