Jump to:

23472 Posts in 18941 Topics by 2878 members

General Questions

SilverStripe Forums » General Questions » Assign to $has_one relationship

General questions about getting started with SilverStripe that don't fit in any of the categories above.

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

Page: 1
Go to End
Author Topic: 2406 Views
  • mh456
    Avatar
    Community Member
    5 Posts

    Assign to $has_one relationship Link to this post

    How does assigning to a $has_one relationship work?

    static $has_one = array(
    "User" => "User"
    );

    I can use
    $o->User = $user;
    or
    $o->UserID = $user->ID;
    but a call to
    $o->User()
    doesn't get the correct result.

    What's wrong here?

  • dalesaurus
    Avatar
    Community Member
    283 Posts

    Re: Assign to $has_one relationship Link to this post

    In case anyone finds this like I do, I will add it to the wiki if some kind folks can review and confirm:.

    Case: $has_one to $has_many

    This can be counter-intuitive, but you must add the ones to the manys through the many.

    class MyObjA extends DataObject {
    $has_many = array('ObjBs' => 'MyObjB');
    }
    class MyObjB extends DataObject {
    $has_one = array('ObjA' => 'MyObjA');
    }

    $b = new MyObjB();
    $a = new MyObjA();

    // Works
    $a->ObjBs()->add($b);
    $a->write();

    // Will not work, nor produce any error
    $b->ObjA = $a;
    $b->write();

    Case: $has_one to $has_one

    I am not 100% on these as I don't have an example handy, but I believe they are access/set by the ID field. Can someone confirm/fix?

    // Starting with this for all below snippets

    class MyObjA extends Dataobject {
    $has_one = array('ObjB' => 'MyObjB');
    }
    class MyObjB extends Dataobject {
    $has_one = array('ObjA' => 'MyObjA');
    }

    $a = new MyObjA();
    $b = new MyObjB();

    // Does not save the relation, no error
    $a->ObjB = $b;
    $a->write();

    // Does not save the relation, no error
    $a->ObjB = $b->ID;
    $a->write();

    // Saves ID of $b into MyObjA.ObjBID field, is NOT mutually saved in $b
    $a->ObjBID = $b->ID;
    $a->write();

    // Nothing saved in MyObjA.ObjBID
    $a->ObjBID = $b->ID;
    $a->write();
    $b->write();

    The last one is puzzling and is probably why some of my multi object setup of relationships aren't being saved.

    • -Does it matter which one of these gets saved? (Answer must be yes, but why?)
    • -If you save $b into $a per the first example to you have to ->write() on both or just one?
    • -How do you ensure that in a 1:1 relationship that both sides of the model are updated with the other object's ID?

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