Silverstripe: Filter blog posts by Author
Asked Answered
B

1

5

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.

Bangweulu answered 25/8, 2016 at 2:37 Comment(0)
R
7

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);
Run answered 25/8, 2016 at 2:52 Comment(1)
Fantastic. Thanks for your help.Bangweulu

© 2022 - 2024 — McMap. All rights reserved.