Dallby Dallby - 3 months ago 59
PHP Question

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.

Answer

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);