Zero foreign key

newbie programmer.

I have 3 tables, namely: product, category and subcategory. I configured their relationship as follows:

Product Category: Many-to-Many
Product in the subcategory: Individual

Subcategory: Multi-to-One

I added a subcategory_id column, which is a foreign key in the product table (for matching product tables and subcategories). This works if the product has a subcategory. Now the problem is that I have products that do not have a subcategory. The subcategory_id column is supposed to be null, but this is not allowed. Is there a workaround for this? I also think that the relationship relationship has something to do with it. Any thoughts?

+4
source share
3 answers

As long as the id_category is NULL, you should be able to add a foreign key that will ensure the integrity of the relationship in all cases where the column is not zero. This is a fairly common use case.

+4
source

Product For Subcategory: One To One

Shouldn't It Be a Product in the Subcategory: Many-to-One

And why is it impossible to make the subcategory_id default null column?

+1
source

Product for category: many-to-many

Product For Subcategory: One To One

Subcategory: Multi-to-One

This makes no sense. If the product and subcategory are the same, then they are one and the same object. Or are they equal to 0/1?

In any case, in any case, if they are from one to one or from one to zero or one, then each product belongs to another subcategory, and each subcategory has no more than one product assigned to it. If so, then it may not be that the products are one for many, and the categories and subcategories are the same for many with the category.

Think about it. If a can be many categories for one Product, but only one subcategory for a Product, then there can be many categories for a subcategory, which is the opposite of what you have for both categories and subcategories: from one to many

Typically, relationships for product categories and subcategories are as follows:

Category for subcategory from one to many (many subcategories for each category - only one category for each subcategory)

Product Subcategory: From one to many, many products may be in each subcategory. but each product is in no more than one subcategory.

Are you sure this is not your structure? ...

0
source

All Articles