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

Dhruva's avatar
Level 11

How to display records in datatable according to column in pivot table?

I have two models. Question and Quiz.

Both are related to each other as belongs To Many relationship. The pivot table 'quiz_questions' contains some extra columns including 'sort_order"

Question.php

  public function quizzes()
  {
        return $this->belongsToMany(\App\Models\Quiz::class, 'quiz_questions')
                    ->withPivot('sort_order', 'section')
                    ->orderBy('quiz_questions.sort_order');
  }

Quiz.php

  public function questions()
  {
        return $this->belongsToMany(\App\Models\Question::class, 'quiz_questions')
                    ->withPivot('sort_order', 'section')
                    ->orderBy('quiz_questions.sort_order');
  }

Query

public function query(): Builder
{
      return Question::query()
            ->select('id', 'text', 'question_type')
            ->with(['quizzes:id,name'])
            ->whereHas('quizzes', fn($q)=> $q
                  ->where('id', $this->quiz->id)
                  ->when($this->getFilter('section'), fn($q, $sectionId)=> $q->where('section_id', $sectionId))
            );
}


I want to display default order of questions  according to pivot column 'sort_order' in increasing order.
But I am not able to figure out.

Kindly guide me.

Thank you.
0 likes
0 replies

Please or to participate in this conversation.