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?
This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.
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.
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?
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.