How to do Inner Join with Laravel?

Asked

Viewed 3,131 times

1

I am studying Laravel and I’m not getting it make/understand how to do join and present the data. All students who are in a class with the names, class code and description of the final situation.

Modelo

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 [codigo_turma] does not exist on this Collection instance.

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

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

  • Luiz needs to put in his question all the classes that are part of this 4 table model! if it is not complicated to answer

1 answer

5


The use of Ner Join does not need to prepare the relationship in models (which is always good to do).

A good tip to prepare an Inner Join, would first check how it works directly in the DBMS of your preference and then put it in the Laravel, this way you are aware of the return and can buy if it is correct

in your case would

$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 example of Inner Join

$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 see more about the Inner Join;

https://laravel.com/docs/5.6/queries#joins

  • Thank you very much!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.