Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何使用Laravel 5/Elount/query builder根据用户的评分获取所有用户订单_Php_Mysql_Laravel_Laravel 5_Eloquent - Fatal编程技术网

Php 如何使用Laravel 5/Elount/query builder根据用户的评分获取所有用户订单

Php 如何使用Laravel 5/Elount/query builder根据用户的评分获取所有用户订单,php,mysql,laravel,laravel-5,eloquent,Php,Mysql,Laravel,Laravel 5,Eloquent,我的数据库中有这些表 用户 id用户名 然后 书籍 id name用户id 评级 id评级簿\u id 现在我想获取所有用户,并将他们列在网页上,但我需要他们按评级排序。所以基本上我需要检查所有用户和他们的书,然后计算这些书的平均评分,然后根据平均评分得到用户 如何使用laravel或查询生成器实现这一点 我有如下关系设置 用户型号 public function books() { return $this->hasMany('App\Book'); }

我的数据库中有这些表

用户

id用户名

然后

书籍

id name用户id

评级

id评级簿\u id

现在我想获取所有
用户
,并将他们列在网页上,但我需要他们按评级排序。所以基本上我需要检查所有用户和他们的书,然后计算这些书的平均评分,然后根据平均评分得到用户

如何使用laravel或查询生成器实现这一点

我有如下关系设置

用户
型号

 public function books()
    {
        return $this->hasMany('App\Book');
    }
 public function ratings()
    {
        return $this->hasMany('App\Rating');
    }
 public function book()
    {
        return $this->belongsTo('App\Book');
    }
书籍
型号

 public function books()
    {
        return $this->hasMany('App\Book');
    }
 public function ratings()
    {
        return $this->hasMany('App\Rating');
    }
 public function book()
    {
        return $this->belongsTo('App\Book');
    }
评级
型号

 public function books()
    {
        return $this->hasMany('App\Book');
    }
 public function ratings()
    {
        return $this->hasMany('App\Rating');
    }
 public function book()
    {
        return $this->belongsTo('App\Book');
    }
另外,如果某本书没有评分,那么我想返回
0
评分,而不是
null
,因此在我的网页中,我可以将用户评分显示为
0

谢谢。

您需要在
User
模型中使用
hasManyThrough
,然后您可以使用
with count
在控制器中获得所需的用户

class User extends Model
{
    function books()
    {
        return $this->hasMany('App\Book');
    }

    function ratings()
    {
        return $this->hasManyThrough('App\Rating', 'App\Book');
    }
}
添加后,在控制器中,您只需执行与上一个问题类似的操作,但使用用户:


谢谢您的回复:)。我需要获得平均评分,而不仅仅是计数,然后需要订购。那么我需要
hasManyThrough
关系吗?如果我这样做,那么在model
ratings
方法中,就不会采用第一个参数,即最终的模型,即
Rating
,而不是
Book
?这是正确的。通过使用
hasManyThrough
可以访问远亲,并使用新的
ratings()
函数在模型中定义远亲。然后你可以在一个雄辩的问题中使用它,就像我在上面的回答中向你展示的那样。谢谢!它解决了我的问题。请更新您的答案。我将
ratings
方法更改为
public function ratings(){return$this->hasManyThrough('App\Rating','App\Book');}
通过更改模型顺序,它可以工作!谢谢。这也可能是我刚刚修正的
App\Ratings
输入错误。