Jump to:

3373 Posts in 998 Topics by 712 members

Data Model Questions

SilverStripe Forums » Data Model Questions » Writing to many_many relationship

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

Page: 1
Go to End
Author Topic: 2026 Views
  • Bambii7
    Avatar
    Community Member
    254 Posts

    Writing to many_many relationship Link to this post

    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();

  • Willr
    Avatar
    Forum Moderator
    5464 Posts

    Re: Writing to many_many relationship Link to this post

    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

  • Bambii7
    Avatar
    Community Member
    254 Posts

    Re: Writing to many_many relationship Link to this post

    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.

  • khanhdeux
    Avatar
    Community Member
    12 Posts

    Re: Writing to many_many relationship Link to this post

    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

    2026 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.