Skip to content
Advertisement

Query builder in Laravel – 2 columns.id foreigns key in a Users.name

I have a problem in my project

I’m trying to do a query with the table “Asignaciones”, this table save the records for students and teachers asignations. (The teachers can comment the works of students and can see only the students that are asigned) The principal problem is that all the users is on the same table and when i try to return a names just have one.

enter image description here

enter image description here

$asignaciones = DB::table('asignaciones')
        ->join('users as students','students.id',
                '=','asignaciones.id_student')
        ->join('users as teachers','teachers.id',
               '=','asignaciones.id_teacher')
        ->select('asignaciones.id','students.name',
                  'teachers.name')->get();

return $asignaciones;

enter image description here

I need to get two names (Maybe changing the column name like a users table) to show in a table

Thanks for your time and answers! 🙂

Advertisement

Answer

Define unique aliases in your select clause for student name and teacher name

->select('asignaciones.id','students.name as student_name','teachers.name as teacher_name');

Right now single alias name is returned for teacher and student name in the returned result set, object cannot have 2 keys with same name so one of the names got override while laravel maps the DB result to object or collection of objects

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement