Jump to:

23481 Posts in 18965 Topics by 2878 members

General Questions

SilverStripe Forums » General Questions » Getting id's from a many to many relation

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

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

Page: 1
Go to End
Author Topic: 1110 Views
  • jacobsjensen
    Community Member
    20 Posts

    Getting id's from a many to many relation Link to this post

    Hello guys,

    Need a little help getting some IDs from a relation table.

    The below code is what i use for a home page. In the administration you can now select multible pages, and the IDs are saved to the relation table "ForsidePage_PreviewList".
    i need to use the IDs from this table in my filter in "ForsidePage_Controller" in the function "showPreviews", and not the hardcoded ...".ID IN (8,9,10)" ...

    How can this be done?

    class ForsidePage extends Page {
    static $db = array();

    static $has_one = array();

       public static $many_many = array(
          'PreviewList' => 'SiteTree'

    function getCMSFields() {
        $fields = parent::getCMSFields();
        $fields->addFieldToTab('Root.Content.Previews', new TreeMultiselectField( 'PreviewList', 'Preview Sites', 'SiteTree'));

        return $fields;

    class ForsidePage_Controller extends Page_Controller {
       function showPreviews() {
       $myIds = "";// Query to get IDs from the relation table
        $records = DataObject::get("WithPreviewPage", "`WithPreviewPage`.ID IN (8,9,10)");
        return ($records);


  • Sean
    Forum Moderator
    921 Posts

    Re: Getting id's from a many to many relation Link to this post

    What you're looking for is a method on the relational getter called getIdList(). To get an array of the IDs of the relation, simply call that method like so (on your controller):


    Then you can just implode the array into a comma separated ID string ready for your SQL query.


Page: 1
Go to Top

Want to know more about the company that brought you SilverStripe? Then check out SilverStripe.com

Comments on this website? Please give feedback.