3

I am working on a SilverStripe project. Now I am querying the data. What I am trying to do is getting all the records running where clause on the count of its relations.

The below query will get all the NewsPage records. NewsPage has many blogs. So, they have a one-to-many relationship:

NewsPage::get();

So if I want to get all the blogs on the news page, I have to do this:

$newPage->BlogPosts()

Now, what I am trying to do is that I am trying to get all the news pages that have more than one blog post:

Something like this arbitrary code

$newPage->where('BlogPosts.Count', '>', 1)->get();

How can I achieve this?

halfer
  • 19,824
  • 17
  • 99
  • 186
Wai Yan Hein
  • 13,651
  • 35
  • 180
  • 372

1 Answers1

4

In SilverStripe 4 we can filter on a $has_many or $many_many relationship count as follows:

NewsPage::get()->filter([
    'BlogPosts.Count():GreaterThan' => 1
]);

For this to work NewsPage must have a $has_many or $many_many relationship to BlogPost called BlogPosts.

3dgoo
  • 15,716
  • 6
  • 46
  • 58