21301 Posts in 5735 Topics by 2603 members
|
Page:
1
|
Go to End | |
| Author | Topic: | 1667 Views |
-
Assign to $has_one relationship

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?
-
Re: Assign to $has_one relationship

1 September 2009 at 5:55am Last edited: 1 September 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?
- -Does it matter which one of these gets saved? (Answer must be yes, but why?)
| 1667 Views | ||
|
Page:
1
|
Go to Top |


