views:

45

answers:

3

Hi! I have 2 entities

  • User
  • UserCreditCard

A user can have a credit card or not. How would you model the relation and why?

Option 1: User has a foreign key to UserCreditCard that may be null

Option 2: UserCreditCard has a foreign key to User that can't be null

EDIT

My mistake not remarking that user will have 0 or 1 credit cards, no more

+2  A: 

I think you already stated how and why you should model it:

A user can have a credit card or not

Go with option 1. You'll be able to tell who has a card and who doesn't by checking the foreign key and your mappings will still work because if the credit card foreign key is null, the credit card won't match to anything so it'll just be null. You'll have to be careful when you delete the credit card that you delete the mapping in the User entity, however.

lewiguez
What if the user has more than one card?
dportas
+3  A: 

I would avoid making a two-way relationship here. It would seem to make more sense to simply model your CreditCard table with a UserID column that references your User table. Adding a CreditCardID reference to User just adds a needless level of complexity and opportunity for error.

I would recommend removing the reference from User to CreditCard and making the reference from CreditCard to User non-nullable and indexed. This should give you everything you need.

Adam Robinson
Thanks adam! My idea is not a two-way relashionship but adding the foreign key only in one table. Trying to decide which side it's better.
Timmy O' Tool
@Timmy: Then go with the latter; a user without a credit card makes sense, a credit card without a user does not. In addition, the second model can allow for multiple cards per user (and can also be restricted to one with a simple unique index), while the first does not. In short, I can't see anything that would possibly direct me to the first option unless you wanted two users to be able to share the same card (which is usually not allowed), and even then I'd probably opt for a M:M relationship rather than going with the first option. **TL;DR version: Don't use the first option.**
Adam Robinson
@Adam: very complete explanation and well justified. Thanks a lot!
Timmy O' Tool
@Timmy: Thanks. If this answers your question, please accept it by clicking the checkmark.
Adam Robinson
Sure Adams, just trying to see if anyone have something else to say. I was expecting to have more opinions :-( Promise to mark as resolved if no one else add anything in short.
Timmy O' Tool
+2  A: 

Go for option two. It has less complexity and it also models the case where a user has more than one credit card, or changed his credit card.

daefu