3069 Posts in 868 Topics by 650 members
|
Page:
1
|
Go to End | |
| Author | Topic: | 1297 Views |
-
Adding a object programatically to a many_many relationship

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 -
Re: Adding a object programatically to a many_many relationship

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
| 1297 Views | ||
|
Page:
1
|
Go to Top |

