Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Silverstripe: Filter blog posts by Author

I've been googling for about 2 hours now and can't find an answer to this question. I'm trying to filter blog posts (using the silverstripe-blog module) by Author/MemberID. So far I've got:

public function MyRecentPosts() {

        $posts = BlogPost::get()
            ->sort('PublishDate','desc')
            ->limit(2);

        return $posts;
    }

Obviously that only returns the most recent blog posts. I'm not sure I understand how to relate the Blog Post table with the BlogPost_Authors table...

Any advice would be greatly appreciated.

like image 613
Dallby Avatar asked Aug 25 '16 02:08

Dallby


1 Answers

Well the BlogMemberExtension is applied to the Member class, which provides you with an easy way to access a member's posts via the "belongs many many" association.

I'm assuming here that this function would not be in an extension of Member, and that you'll pass in the member ID since it's not present in your code already. This assumption may well be incorrect since your method is named "MyRecentPosts", but anyway - here's an example:

public function MyRecentPosts($memberId)
{
    $member = Member::get()->byId($memberId);

    $posts = $member->BlogPosts()
        ->sort('PublishDate', 'desc')
        ->limit(2);

    return $posts;
}

You could also do it from the BlogPost model via its "many many" association:

$posts = BlogPost::get()
    ->filter(array('Authors.ID' => $memberId))
    ->sort('PublishDate', 'desc')
    ->limit(2);
like image 119
scrowler Avatar answered Oct 31 '22 14:10

scrowler