key of the same table

1

Do you talk beauty?

I'm doing an infinite category system, so in the table has the code and code of the parent category. I would like to relate these two fields to when I delete a category the child is deleted too, so I do not need to treat via code.

But how do I do this? Because you imagine that the parent code needs to be registered and if the category is the highest level it will not have parent, giving the key error.

Thank you.

    
asked by anonymous 27.03.2015 / 20:14

1 answer

1

Explaining the response from @Rafael Withoeft :

You must have a foreign key (FK) in your child category table that should reference the parent category code in the child category table and also you must specify that when a child category is deleted, the child_category should be deleted as well. This is done (in MySQL) as follows (assuming you have previously created the tables):

ALTER TABLE 'nome_da_tabela_categoria_filho' 
ADD CONSTRAINT 'fk_categoria_pai' 
FOREIGN KEY ( 'cod_categoria_pai' ) 
REFERENCES 'nome_da_tabela_categoria_pai' ( 'nome_do_cod_categoria_pai' ) 
ON DELETE CASCADE;
    
27.03.2015 / 20:37