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

carcleo's avatar

belongsToMany in Pivot with more than 2 fields

I have the following inside Stdent Model:

public function disciplines()    {
        return $this->belongsToMany(Discipline::class, 'student_discipline_classroom', 'student_id', 'discipline_id')
            ->withPivot('classroom_id') 
            ->withTimestamps();
    }

it give me a return

Bu i need of the field code (not is id) from classroom table.

What i have that ro change?

I am calling it so:

$students = Student::find(2);
dd($students->disciplines->toArray());

i reply that i wish this like

[
Array
(
    [0] => Array
        (
            [discipline] => Expressão Gráfica
            [classroom] => ENG. SOFT 1A 20242 S
        )

    [1] => Array
        (
            [discipline] => Introdução à Engenharia
            [classroom] => ENG. SOFT 1A 20242 S
        )
...
0 likes
3 replies
tykus's avatar
tykus
Best Answer
Level 104

I would just use JOINs and avoid paying the price of multiple Eloquent queries, e.g.

Student::toBase()
  ->selectRaw('classrooms.name as classroom, disciplines.name as discipline')
  ->join('student_discipline_classroom', 'students.id', 'student_id')
  ->join('disciplines', 'disciplines.id', 'discipline_id')
  ->join('classrooms', 'classrooms.id', 'classroom_id')
  ->where('students.id', 2)
  ->first();
carcleo's avatar

@tykus it was that i did. In the true, i would like of to use the BelongTo therefore... Thank you!

tykus's avatar

@carcleo I understand, however, I would counter that you don't need actually need any Model instances for the Response, so instantiating all of those Models is just wasteful.

Please or to participate in this conversation.