Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

rassem's avatar

Simplify query

Is there any way i can simplify this query, Avoiding query in a loop and get all the data in single query!

    foreach ($Subjects as $sub) {
        foreach ($ExamSubHeads as $esh) {
            $IsExist = DB::table('tbl_marks_distributions')
                    ->select('marks_distribution_id', 'full_marks', 'allowed_input_date_time_from', 'allowed_input_date_time_to', 'is_active', 'pass_marks', 'percent')
                    ->where('subject_id', $sub->subject_id)
                    ->where('class_id', $ClassID)
                    ->where('group_id', $GroupID)
                    ->where('institute_branch_version_id', $branchShiftVersion)
                    ->where('exam_type_id', $ExamTypeID)
                    ->where('exam_sub_head_id', $esh->exam_sub_head_id)
                    ->where('exam_head_id', $ExamHead)
                    ->where('academic_year', $Year)
                    ->where('section_id', $Section)
                    ->first();

            if (!empty($IsExist)) {
                $ExistingMarksDistributions[] = array(
                    'ExistingID' => $branchShiftVersion . '-' . $ClassID . '-' . $GroupID . '-' . $ExamTypeID . '-' . $esh->exam_head_id . '-' . $esh->exam_sub_head_id . '-' . $sub->subject_id . '-' . $Year,
                    'MarksDistributionID' => $IsExist->marks_distribution_id,
                    'FullMarks' => $IsExist->full_marks,
                    'InputFrom' => $IsExist->allowed_input_date_time_from,
                    'InputTo' => $IsExist->allowed_input_date_time_to,
                    'IsActive' => $IsExist->is_active,
                    'PassMarks' => $IsExist->pass_marks,
                    'Percent' => $IsExist->percent,
                );
            }
        }
    }
0 likes
2 replies
munazzil's avatar

Use instead of this $IsExist = DB::table('tbl_marks_distributions') ->select('marks_distribution_id', 'full_marks', 'allowed_input_date_time_from', 'allowed_input_date_time_to', 'is_active', 'pass_marks', 'percent') ->where('subject_id', $sub->subject_id) ->where('class_id', $ClassID) ->where('group_id', $GroupID) ->where('institute_branch_version_id', $branchShiftVersion) ->where('exam_type_id', $ExamTypeID) ->where('exam_sub_head_id', $esh->exam_sub_head_id) ->where('exam_head_id', $ExamHead) ->where('academic_year', $Year) ->where('section_id', $Section) ->first(); as like below,

                $IsExist = DB::table('tbl_marks_distributions')
                ->pluck('marks_distribution_id', 'full_marks', 'allowed_input_date_time_from', 'allowed_input_date_time_to', 'is_active', 'pass_marks', 'percent')->first();
rassem's avatar

Can you carefully read the post! I was talking about avoiding using query in a loop.

Please or to participate in this conversation.