简体   繁体   English

根据另一个表中具有雄辩的列表选择十个顶级类别

[英]Selecting ten top categories based on a columnt in another table with eloquent

I have three tables: uploads , categories and a many-to-many table called category_upload . 我有三个表: uploadscategories和名为category_upload many-to-many表。

The tables look like this : 表格如下所示:

**categories**

id
name

**uploads**

id
name
downloads(integer)

**category_upload**

id
category_id
upload_id

Every time I download an "Upload" the value in the downloads column is increased by 1. 每次下载“上传”时,下载列中的值都会增加1。

What I want to do, but couldn't figure out how to even start is to select top 10 categories based on the downloads column in the uploads table. 我想做的,但无法弄清楚如何开始是根据uploads表中的downloads列选择前10个类别。 So, if the total of the downloads column is the biggest for all uploads from a given category this category should be number one and so on to number ten. 因此,如果downloads列的总数对于来自给定类别的所有上载而言最大,则此类别应为第一,依此类推至第十。

Can this be achieved with eloquent or just SQL and how? 这可以通过雄辩或只是SQL来实现吗? Any tips are appreciated! 任何提示表示赞赏!

Here is how I've set up my relationships in the models : 以下是我在模型中建立关系的方式:

Category : 分类:

public function uploads(){
        return $this->belongsToMany('App\Upload');
    } 

Upload : 上传:

public function category(){
    return $this->belongsToMany('App\Category');
}
Select category_id, uploads
From (
    Select category_id, SUM(downloads) as uploads
    From uploads as u
    Left join upload_category as uc on uc.id=u.upload_id
    Left join category as c on c.id=uc.category_id
    Group by  category_id    )as t
  Order by uploads desc
  Limit 10

your Category model 你的Category模型

public function downloads()
{
    return $this->hasMany('App\Upload','category_upload','category_id','upload_id');
}

In your controller( Catagory ) 在你的控制器( Catagory

try this 尝试这个

Category::select("*")->with(['downloads' => function($q){
    $q->oderBy('downloades','desc')->take(10)->get();
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM