wmk
wmk

Reputation: 4626

Silverstripe ORM: sort by number of $belongs_many_many relation

How do I get the most active blog tags in a query?

I have this two DataObjects:

class BlogTag extends DataObject {

//...

    /**
     * @var array
     */
    private static $belongs_many_many = array(
        'BlogPosts' => 'BlogPost',
    );

and

class BlogPost extends Page {

//...

    /**
     * @var array
     */
    private static $many_many = array(
        'Tags' => 'BlogTag',
    );

Now i wonder how I can get a DataList with all BlogTags ordered by how many blog posts they're related to. This is what i have already, but somehow i don't get how to sort by BlogPosts.Count():

public function getPopularBlogTags($limit = 5) {
    $tags = BlogTag::get()
        ->sort('BlogPosts.Count()') //doesn't work
        ->limit($limit);

    return $tags;
}

Upvotes: 3

Views: 893

Answers (1)

wmk
wmk

Reputation: 4626

Found a solution with help on IRC (thanks barry and mark)

public function getPopularBlogTags($limit = 5) {
    $tags = BlogTag::get()
        ->setQueriedColumns(['ID', 'Title', 'Count(*)'])
        ->leftJoin('BlogPost_Tags','bpt.BlogTagID = BlogTag.ID','bpt')
        ->sort('Count(*) DESC')
        ->alterDataQuery(function($query){
            $query->groupBy('BlogTag.ID');
        })
        ->limit($limit);

    return $tags;
}

And in the template:

   <% loop $PopularBlogTags %>
        <a href="$Link" title="$Title">$Title ($BlogPosts.Count())</a>
        <% if not $Last %> | <% end_if %>
    <% end_loop %>

Upvotes: 5

Related Questions