Reputation: 1689
I have faced a tricky problem which I would like to solve eloquent way but I think I would need to get into raw sql, which I do not really want. Here is what I have so far:
User model - user can have many posts id | name
Posts - can have several categories id | user_id | title ... etc
Skills - This is pivot table for many-to-many relationship (skill_types related to posts) id | skill_type_id | post_id
Skill types - this is list of unique skills. id | slug | title | etc..
Votes - votes are related to Skills table
id | skill_id
What I need to do is to get top 10 skills of users with number of votes. For doing it I need to merge skills by name and sum up number of votes, then sort by number of votes and output the top 10.
Probably my brain is too tired today already and I will solve the puzzle tomorrow morning but until I came up with a solution, maybe someone else will help with it.
My Solution:
public function getTopSkills($limit = 10, $offset = 0)
{
$results = DB::select('select skill_types.name as name, count(likes.id) as votes
FROM
skills
left join likes
on skills.id=likes.likeable_id
join posts on skills.item_id = posts.id
join users on posts.user_id = users.id
join skill_types on skill_types.id = skills.skill_type_id
where users.id = :userid
group by skill_types.name
order by votes desc
limit :limit
offset :offset', ['userid' => $this->id, 'limit' => $limit, 'offset' => $offset]);
return $results;
}
Upvotes: 2
Views: 1185
Reputation: 141
Fortunately, the SQL is easier than you think
SELECT skill_id, count(id)
FROM VOTES
group by skill_id
Then you just have to tie skill_id back to the skill type table to get the name instead of a numerical ID
Upvotes: 2