PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, February 10, 2022

[FIXED] How to get average with orderBy Desc in Laravel 5

 February 10, 2022     eloquent, laravel, laravel-5, mysql, php     No comments   

Issue

I have 2 tables in my database.

books and ratings

in books id, name

in ratings

id, book_id, rating

i have set has many relationship for these models.

So in Book model -

public function ratings()
{
    return $this->hasMany('App\Rating');
}

in Rating Model -

public function book()
{
    return $this->belongsTo('App\Book');
}

Now i want to fetch all books with there average rating but order by high rating.

so i high rated books first and then low ratings.

So How i can join 2 tables to achieve this result.

Thanks.


Solution

You can use a modified withCount():

$books = Book::withCount(['ratings as average_rating' => function($query) {
    $query->select(DB::raw('coalesce(avg(rating),0)'));
}])->orderByDesc('average_rating')->get();


Answered By - Jonas Staudenmeir
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing