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.

General Questions /

General questions about getting started with SilverStripe that don't fit in any of the categories above.

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

Fetching Objects by their many_many relations


Go to End


796 Views

Avatar
Andre

Community Member, 146 Posts

8 July 2011 at 9:21am

Hi there,

I'm trying to fetch some objects by their many_many relations.

The Dataobjects look the following:

class Asset extends DataObject {
    static $db = array(
        'Title' => 'Varchar',
        'IsActive' => 'Boolean'
    );

    static $many_many = array(
        'Countries' => 'Country',
        'Languages' => 'Language'
    );
}

class Language extends DataObject {
    static $db = array(
        'Title' => 'Varchar'
    );

    static $belongs_many_many = array(
        'Assets' => 'Asset'
    );
}

class Country extends DataObject {
    static $db = array(
        'Title' => 'Varchar'
    );

    static $belongs_many_many = array(
        'Assets' => 'Asset'
    );
}

Countries and Languages will be a smaller number, about 20-40 each. But Assets there will be up to a few 1000.

Now I want to get all Assets which do exist for a selected number of Countries and Languages. The Selections should work the following. If an Asset exists for the selected Countries, but not for the selected Languages, it should not been chosen. Only if the Asset matches at least one of the selected countries AND one of the selected languages.

How do I get these Assets at best. One Idea is, to fetch all Asset IDs by country, then fetch from these IDs by language and then fetch all Dataobjects with the left IDs. Another would be a left join, which I'm unable to create for the moment.

What would be the best way under the aspect of performance? And How do I fetch only the IDs of a belongs_many_many relation without querying the Database to much?

thanks for your advices