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

How to implement "up to one" relations


Go to End


3 Posts   1591 Views

Avatar
HansR

Community Member, 141 Posts

26 February 2010 at 11:59am

Hi,

I have the Silverstripe book, which describes the Object Relational Model (ORM). While it's very clear what a "has one" relation is, or "one to many," how would you implement an "up to one" relation? Or, for that matter, a relation with 0 to many objects?

Why would someone want this? Well, let's assume that you have an online store, and some products have a downloadable demo, but others don't. An "up to one" relation would be the easiest way to implement this. Likewise, some products may have one or more user reviews, but others might not.

I'm not familiar with SQL, but I have read that not all databases allow NULL keys, and you have to explicitly ask for a database column to allow null entries. So, how would "up to one" type relations be implemented? And can this be done in Silverstripe without resorting to direct SQL queries?

Hans

Avatar
Willr

Forum Moderator, 5523 Posts

26 February 2010 at 3:15pm

I'm not completely sure why you would need a up to one. Has one relationships can be non existent (eg if a page has one image - it could actually have no images) so the naming 'has_one' is a bit confusing. In the database it stores 0 - which evaluates $this->Image() as false.

Same with has many and many many. They both happily support no records - if you call $this->Images() it returns a component set so you need to call $this->Images()->exists() to check that at least 1 record exists.

Avatar
HansR

Community Member, 141 Posts

26 February 2010 at 4:53pm

Thanks, that's exactly what I was looking for. I assumed that it already existed somewhere in the system, but I didn't see anything to confirm it or not. Things such as UML make the distinction between 1-to-1 and 1-to-0:1, hence the confusion.

Hans