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.
That query would look something like this:
You need to join the two tables, use an aggregate function with a group by on the book. Then just sort and limit the results.
UPDATE:
In response to your question:
Use of a
view
might be something of a compromise between ease of the ORM and sanity in your querying.You can use a modified
withCount()
:Via Collections*
Via Joins