Skip to content

Instantly share code, notes, and snippets.

@mass6
Created February 25, 2015 10:39
Show Gist options
  • Save mass6/04b9c3186fb2f48f9d9c to your computer and use it in GitHub Desktop.
Save mass6/04b9c3186fb2f48f9d9c to your computer and use it in GitHub Desktop.
Returns the related a an aggregate list of related (many-many) models by the count of related models. Fx. return all tags in order of amount of associated posts they have.
$tagsList = $this->tag->select(DB::raw('tags.name, count(tags.id) as occurrences'))
->join('post_tag', 'tags.id', '=', 'post_tag.tag_id')
->join('posts', 'posts.id', '=', 'post_tag.post_id')
->groupBy('tag_id')
->orderBy('occurrences', 'desc')
->limit(12)
->get();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment