Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get same named columns separately after left join in mysql using Eloquent

I have 2 tables one of them stores students and the other one managers

students have name surname, eventually managers have name and surname too.

I also store added_by in students table to check which manager added the student.

With the query I join tables

   $students = \App\Student::with('payment')->with('discontinuities')
                ->leftJoin('managers','students.added_by','=','managers.id')
                ->get();

lets say student is

Name Surname Added_by

Jon Doe 1

and Manager is

id name surname

1 jane doe

So when I join those 2 tables with the query I give above. My student becomes

Jane doe because of name conflicts in those 2 tables.
Simply manager's name overwrites to student's name since both columns named same.

I could actually join only some columns in managers table however I need this name column to print out added_by column with the managers name and of course I can change columns name to something else in a table however this would be too much work because I have to refactor each query in my application one by one and also test everything from scratch

so my question is how can I join those 2 tables and prevent conflictions on columns with same name?

like image 684
Anar Bayramov Avatar asked Feb 08 '23 22:02

Anar Bayramov


1 Answers

Try using this:

$students = \App\Student::with('payment')->with('discontinuities')
    ->leftJoin('managers','students.added_by','=','managers.id')
    ->select('students.*','managers.name as m_name','managers.surname as m_s_name','managers.other_column_if_needed','managers.another_column_if_needed')
    ->get();

This way your managers table's name column will be treated as m_name and surname column will be treated as m_s_name

like image 68
smartrahat Avatar answered Feb 11 '23 17:02

smartrahat