Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

We've moved the forum!

Please use forum.silverstripe.org for any new questions (announcement).
The forum archive will stick around, but will be read only.

You can also use our Slack channel or StackOverflow to ask for help.
Check out our community overview for more options to contribute.

Data Model Questions /

Moderators: martimiz, Sean, Ed, biapar, Willr, Ingo, swaiba

Sub-query, group and having in SilverStripe ORM


Go to End


2 Posts   723 Views

Avatar
FlamyTwista

Community Member, 4 Posts

21 February 2017 at 3:07am

I'm using SilverStripe ORM.

I need to get all companies that are at least in ALL of the desired Specializing (no less):

class CompanyPage extends Page {    
    private static $many_many = [
        "Specializings" => "Specializing",
    ];
}

class Specializing extends DataObject {
    private static $belongs_many_many = [
        "CompanyPages" => "CompanyPage",
    ];
}

I have an array filled with desiring specializing ids ( $specIds ).
This gets companies that are at at least in one of the desired specializing, but it isn't that I need.
$companyPages = CompanyPage::get()->filter([
    "Specializings.ID:ExactMatch" => $specIds,
]);

I can achive my task with this SQL-query
select * from CompanyPage c1 join (
  select c.ID from CompanyPage c 
  join CompanyPage_Specializings cs on cs.CompanyPageID = c.ID
  where cs.SpecializingID in (14,15)
  group by c.ID having count(c.ID) = 2
) c2 on c1.ID = c2.ID

But how can I achive it with SilverStripe ORM?
I can't find anything about having by aggregated functions in ORM

Avatar
FlamyTwista

Community Member, 4 Posts

25 February 2017 at 1:25am