Two columns with the same name

2

I have a problem with the query I'm doing, when joining two tables with a join I do not see a column because they have the same name. I tried to use a select as I normally do in sql but it still does not appear.

$user = DB::table('app_registro_usuario')
        ->join('app_alumno_curso', 'app_alumno_curso.id_alumno', '=', 'app_registro_usuario.id')
        ->join('app_curso', 'app_alumno_curso.id_curso', '=', 'app_curso.id')
        ->join('app_sexo', 'app_registro_usuario.id_sexo', '=', 'app_sexo.id')
        ->where('id_tipo_usuario', 1)
        ->where('app_registro_usuario.id', $id)
        ->where('id_estalecimiento', $id_establecimiento)
        ->first();

The name of the column that is in two tables that I connect is "name".

    
asked by Gustavo 19.02.2018 в 14:29
source

2 answers

1

You can use the word as within the select() to assign aliases to the columns or use a selectRaw()

Examples

With select()

$user = DB::table('app_registro_usuario')

 ->select('app_curso.nombre as nombre_curso', 'app_registro_usuario.nombre as nombre_usu')

        ->join('app_alumno_curso', 'app_alumno_curso.id_alumno', '=', 'app_registro_usuario.id')
        ->join('app_curso', 'app_alumno_curso.id_curso', '=', 'app_curso.id')
        ->join('app_sexo', 'app_registro_usuario.id_sexo', '=', 'app_sexo.id')
        ->where('id_tipo_usuario', 1)
        ->where('app_registro_usuario.id', $id)
        ->where('id_estalecimiento', $id_establecimiento)
        ->first();

With selectRaw()

$user = DB::table('app_registro_usuario')

->selectRaw('app_curso.nombre nombre_curso, app_registro_usuario.nombre nombre_usu')

        ->join('app_alumno_curso', 'app_alumno_curso.id_alumno', '=', 'app_registro_usuario.id')
        ->join('app_curso', 'app_alumno_curso.id_curso', '=', 'app_curso.id')
        ->join('app_sexo', 'app_registro_usuario.id_sexo', '=', 'app_sexo.id')
        ->where('id_tipo_usuario', 1)
        ->where('app_registro_usuario.id', $id)
        ->where('id_estalecimiento', $id_establecimiento)
        ->first();
    
answered by 19.02.2018 / 14:49
source
1

You can assign an alias other than differentiate them with the name of the table of each corresponding field, all this you do in the select:

->select('tabla1.nombre as nombre1', 'tabla2.nombre as nombre2')
    
answered by 19.02.2018 в 14:47