Jump to:

3460 Posts in 1064 Topics by 739 members

Data Model Questions

SilverStripe Forums » Data Model Questions » Adding a object programatically to a many_many relationship

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

Page: 1
Go to End
Author Topic: 1873 Views
  • mco
    Avatar
    Community Member
    14 Posts

    Adding a object programatically to a many_many relationship Link to this post

    Hi,

    I have a many_many relationship in my Page class to a Tag class.

    * MyPage extends SiteTee
    * Tag extends DataObject
    * MyPage many_many -> (Tags, Tag)
    * Tag belongs_many_many (MyPages, MyPage)

    Now I'm importing stuff from a XML file and create Pages from it. I want to assign the Tags form my XML to the newly created page.

    Here is the pseudo-code:

    $page = new MyPage();
    $page->ParentID = $parentID
    $page->Title = $title;
    $page->Content = $content;

    $tag = DataObject::get_by_id("Tag", (int)$myTagID);
    $page->Tags()->push($tag, $tag->ID);
    $page->writeToStage('Stage');

    Well, the page is create fine, but it has no refference to the Tag specified... Is it right to call $page->Tags()->push(...) ?
    $page->Tags()->write() didn't was no good as well...

    thanks,
    mco

  • mco
    Avatar
    Community Member
    14 Posts

    Re: Adding a object programatically to a many_many relationship Link to this post

    OK that's strange...

    It works after doing the writeToStage() before calling $page->Tags()->add()

    so failing code looks like this:

    $page = new MyPage();
    $tag = DataObject::get_by_id("Tag", (int)$myTagID);
    $page->Tags()->push($tag, $tag->ID);
    $page->writeToStage('Stage');

    working code looks like this:

    $page = new MyPage();
    $tag = DataObject::get_by_id("Tag", (int)$myTagID);
    $page->writeToStage('Stage');
    $page->Tags()->push($tag, $tag->ID);

    At the end it makes sens if you think about it. We need to have the ID of the page to write it's relation to the MyPage_Tags table. When creating a new Page you need to write it to the DB to get it's ID.

    cheerz,
    mco

    1873 Views
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.