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're retiring the forums!

The SilverStripe forums have passed their heyday. They'll stick around, but will be read only. We'd encourage you to get involved in the community via the following channels instead:

Data Model Questions /

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

Adding a object programatically to a many_many relationship


Go to End


2 Posts   3446 Views

Avatar
mco

Community Member, 14 Posts

5 July 2010 at 8:52pm

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

Avatar
mco

Community Member, 14 Posts

5 July 2010 at 9:33pm

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