Deekshith's avatar

Use pagination with DB:select()

i have a query like below,

$notattemptedquestions = DB::select( DB::raw("SELECT * FROM questions WHERE test_id = :test_id and active = 1 and question_id NOT IN ( SELECT question_id from user_answers where user_test_id = :user_test_id )"), array(
         'test_id' => $test_id,
         'user_test_id' => $user_test_id,
        ));

I want to add pagination in the above code. how can i add pagination to array? Any idea about converting above query to eloquent?

0 likes
4 replies
Sergiu17's avatar

Something like this, I didn't test it, but should work

DB::table('questions')
            ->where('test_id', $test_id)
            ->where('active', 1)
            ->whereNotIn(
                'question_id',
                DB::raw(
                    'SELECT question_id from user_answers where user_test_id = :user_test_id',
                    [
                        'user_test_id' => $user_test_id
                    ]
                )
            )
            ->paginate();
Sergiu17's avatar
Sergiu17
Best Answer
Level 60

@Deekshith ahh yes, sorry, DB::raw should be wrapped in a select

or

DB::table('questions')
    ->where('test_id', $test_id)
    ->where('active', 1)
    ->whereNotIn(
        'question_id',
        DB::table('user_answers')->select('question_id')->where('user_test_id', $user_test_id)->get()->toArray()
    )
    ->paginate();
Deekshith's avatar

@Sergiu17 Great. Thank you. i have changed like below and used pluck to avoid convert error,

Object of class stdClass could not be converted to string

Below code is working fine. Please let me know the feedback.

$notattemptedquestions = Question::with('questioncategory')->whereHas('questioncategory')
                ->where('test_id', $test_id)
                ->where('language', $user_test_det->test_language)
                ->where('active', 1)
                ->whereNotIn(
                    'question_id',
                    DB::table('user_answers')->where('user_test_id', $user_test_id)->pluck('question_id')
                )
                ->paginate(20);
1 like
Deekshith's avatar

Sorry for the late response. it worked fine and thank you so much.

Please or to participate in this conversation.