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.

General Questions /

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

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

Assign to $has_one relationship


Go to End


2 Posts   5868 Views

Avatar
mh456

Community Member, 5 Posts

1 June 2009 at 12:03pm

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?

Avatar
dalesaurus

Community Member, 283 Posts

1 September 2009 at 5:55am

Edited: 01/09/2009 10:35am

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?