Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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.

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. 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.

Can this be achieved with eloquent or just SQL and how? 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');
}
like image 930
incense_stick Avatar asked Nov 08 '22 13:11

incense_stick


1 Answers

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
like image 96
tyro Avatar answered Nov 14 '22 20:11

tyro