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

Deekshith's avatar

laravel relations with count

Hi , I have tables with below table structure

UserTest Model with columns names (user_test_id(primary), test_id, marks_scored,status) Question model with column names (question_id (primary), test_id, question_text,correct_option) UserAnswer model with column names (user_answer_id (primary) , user_test_id (foreign), user_answer, question_id)

i have three requirement to get total questions in a particular usertest and total attempted, correct and incorrect questions in single query using relationship,

right now i am using below query to display total attended questions,

$user_tests_det = UserTest::withCount(['answers as totalattempt' => function($query) {

                           $query->select(DB::raw('count(user_answers.user_answers_auto_id)'));

                        }])->where('user_id',$user_id)->where('user_test_id',$data['user_test_id'])->first();

above query returns correct answer for total attempted questions

my three models are,

UserTest.php

public function answers() {

return $this->hasMany('App\UserAnswer','user_test_id','user_test_id');

} UserAnswer.php

public function questionsbaselist() { return $this->belongsTo(Question::class,'question_id','question_id'); }

public function questionslist() { return $this->questionsbaselist()->where('questions.correct_option','=','user_answers.user_answer'); } I want to display correct answers count which matches user answers user answer and questions correct option (user_answers.user_answer = questions.correct_option) And also the count of inncorrect attempt (user_answers.user_answer != questions.correct_option)

Please help me out as i tried with all ways and not getting this.

0 likes
0 replies

Please or to participate in this conversation.