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.

Data Model Questions /

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

Writing to many_many relationship


Go to End


4 Posts   6443 Views

Avatar
Bambii7

Community Member, 254 Posts

8 September 2009 at 4:59pm

has anyone got any hints on writing to a many_many relationship? I'm just starting to understand dataobjects a little better and trying to build some forms... the wiki is awesome for info but I can't find anything on saving relationships.

The following is what I have in my head but not too sure how it all fits together

$myDataObject = new myDataObject;
$myDataObject->relationship = form data;
$myDataObject->write();

Avatar
Willr

Forum Moderator, 5523 Posts

8 September 2009 at 5:40pm

a many_many is just a link between 2 dataobjects. Note you will need to write() both objects before you add it to the relationship as the ID of the object is created on write()

// MyDataObject has a many_many to MyOtherDataObject called 'Others'

$dataobject = new MyDataObject();
$dataobject->write();

$other = new MyOtherDataObject();
$other->write();

$dataobject->Others()->add($other);

// you should see a MyDataObject_Others table in your database with 1 entry

Avatar
Bambii7

Community Member, 254 Posts

8 September 2009 at 5:57pm

Thanks for the fast reply willr!
That makes a little more sense. So I imagine I'll be able to add relationships to existing dataobjects by

$dataObject = DataObject::get('mydataobject');
$other = DataObject::get('another');

$dataObject->Others()->add($other);

I'll give it ago. Thnks man.

Avatar
khanhdeux

Community Member, 13 Posts

20 December 2013 at 7:08am

Hi Will, you know when we add successully how to update it because the add function wont update when we change the existing value of the field