Convert sql to query Builder - Laravel

Asked

Viewed 397 times

0

I’m starting at Laravel and I have doubts about eloquent. Could someone help me convert that code SQL in eloquent?

SELECT COUNT(d.id) as total, d.nome_disciplina FROM bd_assuntos as a INNER 
JOIN bd_disciplinas as d on d.id = a.id_disciplina GROUP BY d.id
$count_disciplina = DB::table('bd_assuntos as t')
    ->select('count() as total', 'd.nome_disciplina', 't.nome_assunto')
    ->join('bd_disciplinas as d', 't.id_disciplina', '=', 'd.id')
    ->orderBy('d.id') ->get(); 
  • Gleyson, welcome to Stackoverflow PT, please take a [tour] through the platform to understand how it works and how to formulate your questions.

  • Please put in your post the code you’ve already tried to do and why it didn’t work, your question is looking more like a "do it for me" than a "do it for yourself," by the way, have you entered the Laravel documentation? https://laravel.com/docs/7.x/queries

  • Yes, I’ve been in the documentation and several videos and courses, but this part has taken me seriously.

  • $count_disciplina = DB::table('bd_assuntos as t') ->select('Count() as total', ’d.discipline', ’t.subject_name') ->Join('bd_disciplinas as d', ’t.id_disciplina', '=', ’d.id') ->orderby(’d.id') ->get();

1 answer

0

You can use selectRaw instead of select, and add the groupBy clause with eloquent methods.

I believe that one of the return errors you are receiving is from the database itself, indicating that the fields name_discipline and name_subject are not part of an aggregation.

$count_disciplina = DB::table('bd_assuntos as t')
    ->selectRaw('count() as total', 'd.nome_disciplina', 't.nome_assunto')
    ->join('bd_disciplinas as d', 't.id_disciplina', '=', 'd.id')
    ->groupBy('d.nome_disciplina')
    ->groupBy('t.nome_assunto')
    ->orderBy('d.id') ->get(); 

Browser other questions tagged

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