Jump to:

3372 Posts in 998 Topics by 712 members

Data Model Questions

SilverStripe Forums » Data Model Questions » How to implement "up to one" relations

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

Page: 1
Go to End
Author Topic: 887 Views
  • HansR
    Avatar
    Community Member
    140 Posts

    How to implement "up to one" relations Link to this post

    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

  • Willr
    Avatar
    Forum Moderator
    5462 Posts

    Re: How to implement "up to one" relations Link to this post

    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.

  • HansR
    Avatar
    Community Member
    140 Posts

    Re: How to implement "up to one" relations Link to this post

    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

    887 Views
Page: 1
Go to Top

Want to know more about the company that brought you SilverStripe? Then check out SilverStripe.com

Comments on this website? Please give feedback.