如何通过Laravel 5中的Desc获得平均 [英] How to get average with orderBy Desc in Laravel 5

查看:69
本文介绍了如何通过Laravel 5中的Desc获得平均的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据库中有2个表.

I have 2 tables in my database.

booksratings

idname

ratings

idbook_idrating

我为这些模型设置了很多关系.

i have set has many relationship for these models.

因此在Book模型中-

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

Rating模型中-

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.

所以我如何联接2个表以实现此结果.

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

谢谢.

推荐答案

您可以使用修改后的withCount():

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

这篇关于如何通过Laravel 5中的Desc获得平均的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆