Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

177
Visualizações
Make an order from avg() function

I'm currently working on one Laravel app and I would like to have this one section where top rated books are shown. I stored my ratings in Rating model. My idea was like this below, but, indeed, it didn't work. I would be really, really happy if someone answered me correctly.

$book = Book::all();
$ratings = Rating::where('book_id', '=', $book->id)->orderBy(avg('rating'));
return view('toprated')->withRatings($ratings);

toprated.blade.php

@foreach($ratings as $rating)
    {{ $rating }}
@endforeach
over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

You can update your code like:

$ratings = Articles::where('state', '=', '1')
   ->select(array('ratings.*',
       DB::raw('AVG(rating) as ratings_average')
       ))
   ->orderBy('ratings_average', 'DESC')
   ->get();
over 4 years ago · Santiago Trujillo Relatório

0

If you need to use a MYSQL function, use orderByRaw:

$ratings = Rating::where('book_id', '=', $book->id)->orderByRaw("avg(rating)");
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda