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.

Data Model Questions /

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

saving a has_one relation


Go to End


8 Posts   4053 Views

Avatar
bartvanirsel

Community Member, 96 Posts

6 January 2011 at 10:45pm

Hi!

I am wondering if this is the way to save my has_one relation.
It works, but it's not a nice way.

$Website = new Website();
$form->saveInto($Website);
$Website->MaintainerID = $Member->ID;
$Website->write();

Avatar
swaiba

Forum Moderator, 1899 Posts

7 January 2011 at 1:37pm

I'm curious too - I've used $dataobject->setComponent('Maintainer',$Member->ID) I think, but more often for has_many / many_many - but I normally do it like you have posted...

Avatar
dhensby

Community Member, 253 Posts

10 January 2011 at 4:06am

What's wrong with saving the has_ones in that way?

Avatar
bartvanirsel

Community Member, 96 Posts

10 January 2011 at 9:53pm

There's nothing wrong with it. It works ok, but I was wondering if there is a better/ nicer way to do:

$Website->MaintainerID = $Member->ID; 

A way in which you don't have to involve the ID. Is there a method in the data object which couples and saves these has_one relations for you?

Avatar
martimiz

Forum Moderator, 1391 Posts

13 January 2011 at 1:33am

At least a DropdownField in the CMS would work in situations where you 'd want to choose from (a limited amount of) available 'has_ones'...

Avatar
bartvanirsel

Community Member, 96 Posts

18 January 2011 at 6:21am

yep that's true. I'm saving Member->ID so checking if Member object exists before saving should also do the trick.
Guess we'll have to stick to this way of saving the relation.

Avatar
bcc2k

Community Member, 4 Posts

25 February 2011 at 2:54am

It would be great if a future ss version could support something like the following:

$Website->Maintainer = $Member; 

For now I use the following as a work-around:

$Website->Maintainer = $Member;
$Member->Websites()->add($Website);

but this hack doesn't work of course if you have just one-way many to one (unidirectional).

best regards
andi

Avatar
Willr

Forum Moderator, 5523 Posts

25 February 2011 at 5:06pm

bcc2k any feature requests should go to open.silverstripe.org. I think having it behave like that would be a practical feature. Not sure of the implications or why it doesn't do it currently.