0
votes

I have 2 models: Order and Widget. A Widget is a unique item that can only exist on one Order. I could represent this with belongsTo, namely a Wiget belongsTo an Order and the Widget would contain an order_id field. Or, I could to hasAndBelongsToMany with a join table.

Since a Widget exists on it's own and gets associated to an Order later, is it "okay" for the order_id field on Widget to remain empty? It seems "unclean" to me versus having the join table that associates it to an Order at some time in the future. I also have a need to get Widgets that are associated to an Order and the ones that are not.

What is the best way to set this up?

1

1 Answers

1
votes

I would use belongsTo with the foreign key allowed to be null. It may seem unclean, but I consider it the best alternative, next to HABTM, if you stated that the Widget can exist in just one Order. Having a join table just to associate one record to another seems rather messy.

If you need to get Widgets that have Orders and the ones that don't, just do a filter with order_id = null. Or if you do a find with Containable Behaviour, if the Widget has an order_id null, then the record simply won't be retrieved.