[英]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
. 我有三个表:
uploads
, categories
和名为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.