Let’s say I have an Order model which must have a status. This status could be pending, cancelled, completed, etc.
A) Some people would create a Status model with an id and a description. Then the Order would receive one constant for each seeded status and status_id would be added to the database table.
B) Other people would just create a status string attribute in Order model and validate it across a list of valid values.
Which one do you think is the best way to solve this problem?
Do you know any articles discussing a similar problem?
(I could not find any, may be I am using the wrong search keywords).
I work on legacy codebase that uses a lot of foreign keys for values. So in some scenarios I join to 5 tables to get meaningful data to display to the user.
My preference now is to perform a hybrid of the two. I would create a lookup table with the statuses as the only column (no id and no datetime stamps). The status is made the primary key for the table. Then in my orders table I would store the string value of the status and it would maintain a foreign key relation to the statuses table by the string value.
This maintains integrity of your data by foreign keys, but eliminates the joins. Since the lookup table is usually fairly small, I have seen zero impact on performance.
I would say it depends on whether the status has any more meaning than just a string.
If it’s simply being used as a lookup to see how to treat an Order then I’d just use a constant on the class and validate against that.
If there’s a lot more logic in how an Order moves from one status to another then it seems like a good job for a state machine where very specific logic changes the state of the Order.