Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Database Design: Circular dependency

Imagine the following database:

Table 'companies' has fields id, name and flagship_product_id. Table 'products' have fields id, name and company_id.

A company must have a flagship product (1:1 relationship) and all products have one company (1:N relationship).

When using a storage engine such as MyISM, there shouldn't be any problem with the above scenario, but when using an engine such as InnoDB, problems result when INSERTing new data.

What is a good solution except allowing a NULL relationship for the initial INSERT?

To summarize, A company must have one flagship product.

like image 579
LiraNuna Avatar asked Sep 07 '09 01:09

LiraNuna


1 Answers

You're either going to have to allow NULLs in flagship_product or reconsider how you model this situation. Consider putting flagship_product as a boolean field on product instead. Then you don't have a circular dependency. Or have a product_type field on product that might have values like FLAGSHIP or NORMAL or OBSOLETE or whatever. Of course you have to enforce that but in the past I've found it a cleaner solution to this kind of problem.

like image 70
cletus Avatar answered Sep 28 '22 09:09

cletus