How to do inner join with Laravel?

1

I'm studying Laravel and I'm not able to how to join and display the data. All students who are in a class with the names, class code and description of the final situation.

  

Model: TurmasHasEstudantes

public function turmaid() 
{
    return $this->hasMany(TurmasIdentificacao::class, 'id', 'turma_id');
}

Controller: TurmasHasEstudantesController

$turmax= $turmas_has_estudantes->turmaid;

print_r($turmax->codigo_turma);

Returns the following error:

  

Property [file_code] does not exist on this collection instance.

If I remove the ->codigo_turma I can see all the data in the class.

I need to get:

  

turmas_has_estudantes.id, turmas_has_estudantes.turma_id, turmas_has_estudantes.estudante_id,turmas_has_estudantes.situacao_final_id, estudantes_identificacao.nome, turmas_identificacao.codigo_turma, situacao_final.descricao

    
asked by anonymous 25.03.2018 / 21:46

1 answer

3

The use of the inner join there is no need to prepare the relationship in the models (which is always good to do).

A good hint for preparing an inner join would be to first check how it works right in the DBMS of your choice and then put it in laravel, that way you are aware of the return and can buy if it is correct

In your case it would be

$resultado = DB::table('turmas_has_estudantes')
    ->join('estudantes_identificacao', 'estudantes_identificacao.id', '=', 'turmas_has_estudantes.estudante_id')
    ->join('situacao_final', 'situacao_final.id', '=', 'turmas_has_estudantes.situacao_final_id')
    ->join('turmas_identificacao', 'turmas_identificacao.id', '=', 'turmas_has_estudantes.turma_id')
    ->select('campos_a_serem_pesquisados')
    ->get();

an inner join example

$users = DB::table('users')
    ->join('contacts', 'users.id', '=', 'contacts.user_id')
    ->join('orders', 'users.id', '=', 'orders.user_id')
    ->select('users.*', 'contacts.phone', 'orders.price')
    ->get();

You can read more about the inner join;

link

    
28.03.2018 / 14:08