key from the same table

Asked

Viewed 69 times

1

Talk about beauty?

I’m doing an infinite category system, so the table has the code and code of the parent category. I wanted to relate these two fields for when I delete a category the child is deleted tbm, so I don’t need to treat via code.

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

Thank you.

  • 2

    Foreign Key no campo categoria_pai > e usar: ON DELETE CASCADE ? Could put the table structure together with your question?

1 answer

1

Explaining the response of @Rafael Withoeft:

You must have a foreign key ( FK) in your table categoria_son that should reference the parent category code table categoria_pai and should also specify that when a categoria_pai is excluded, the categoria_fiho 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;
  • Thanks, I think it makes it clearer to himself..

Browser other questions tagged

You are not signed in. Login or sign up in order to post.