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

Deekshith's avatar

if condition inside the query,

Hi, I have below query to get total no of questions,

Tables structre,

tests => 'test_id','test_name','test_type';
user_tests =>user_test_id,marks_scored,time_taken,user_id
questions => question_id, question_text, a,b,c,d,correct_option,question_level,language
user_answer => user_answer_id,user_test_id,question_id,user_answer,

So here i am fetching total number of easy questions user attended.

public function getQuestionLevelcorrectincorrectCount($level,$user_testids,$testids,$languages,$action)
  {

  $correctattempt = UserAnswer::leftjoin('questions','user_answers.question_id','=','questions.question_id')
                                        ->leftjoin('user_tests','user_answers.user_test_id','=','user_tests.user_test_id')
                                        ->where('user_tests.user_id',uid())
                                        ->whereIn('user_tests.user_test_id',$user_testids)
                                        ->whereIn('questions.language',$languages)
                                        ->where('questions.question_level',$level);
  /* All different scenarios */
  switch ($action) {
      case ('correct'):
          $correctattempt->whereColumn('user_answers.user_answer','questions.correct_option');
          break;
      case ('incorrect'):
          $correctattempt->whereColumn('user_answers.user_answer','!=','questions.correct_option');
          break;
  }

    return $correctattempt->count();
  }

it will return the number like 30,

So every question will have 2 marks for test_type 1 and 2.5 marks for test_type 2,

i am using below approach to calculate the marks,

if($testdet->csat > 0) {

            $cat['easy_total_marks'] = $cat['easy_total_question'] * 2.5;
            $cat['easy_marks_scored'] = round(($cat['easy_correct_attempt'] * 2.5) - ($cat['easy_incorrect_attempt'] * (5/6)),2);


          } else {

            $cat['easy_total_marks'] = $cat['easy_total_question'] * 2;
            $cat['easy_marks_scored'] = round(($cat['easy_correct_attempt'] * 2) - ($cat['easy_incorrect_attempt'] * (2/3)),2);
          }

how to put this condition in first part of query only instead of repeating in foreach? i want to edit getQuestionLevelcorrectincorrectCount() function to calculate marks as well.

0 likes
1 reply

Please or to participate in this conversation.