2
Starting with Valdeir Psr’s comment, "category" and "subcategory" tables would be a single table. There would be a field parent_id
that would be NULLABLE
referencing the parent category.
To prevent categories from repeating, place a UNIQUE CONSTRAINT
in nome
and parent_id
together.
There should be an image table. I don’t know if you can have different products with the same image. If you can, the relationship between "image" and "product" would be N:N, otherwise it would be 1:N. I’ll assume it’s N:N.
In the "promotion" table, I would not recommend using float
for the price. I suggest NUMERIC(10, 2)
or similar thing.
Would look like this:
CREATE TABLE categoria (
id INT(11) NOT NULL AUTO_INCREMENT,
parent_id INT(11) NULL,
nome VARCHAR(45) NOT NULL,
ativo TINYINT NOT NULL,
CONSTRAINT pk_categoria PRIMARY KEY (id),
CONSTRAINT fk_categoria_parent FOREIGN KEY (parent_id) REFERENCES categoria (id),
CONSTRAINT uk_categoria UNIQUE (parent_id, nome)
) ENGINE=InnoDB DEFAULT CHARACTER SET=utf8mb4;
CREATE TABLE imagem (
id INT(11) NOT NULL AUTO_INCREMENT,
nome VARCHAR(65) NOT NULL,
CONSTRAINT pk_imagem PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARACTER SET=utf8mb4;
CREATE TABLE produto (
id INT(11) NOT NULL AUTO_INCREMENT,
categoria_id INT(11) NOT NULL,
nome VARCHAR(65) NOT NULL,
descricao TEXT(3000) NOT NULL,
data_entrada DATE NOT NULL,
ativo TINYINT NOT NULL,
CONSTRAINT pk_produto PRIMARY KEY (id),
CONSTRAINT fk_produto_categoria FOREIGN KEY (categoria_id) REFERENCES categoria (id),
CONSTRAINT uk_produto UNIQUE (nome)
) ENGINE=InnoDB DEFAULT CHARACTER SET=utf8mb4;
CREATE TABLE produto_imagem (
produto_id INT(11) NOT NULL,
imagem_id INT(11) NOT NULL,
CONSTRAINT pk_produto_imagem PRIMARY KEY (produto_id, imagem_id),
CONSTRAINT fk_produto_imagem_produto FOREIGN KEY (produto_id) REFERENCES produto (id),
CONSTRAINT fk_produto_imagem_imagem FOREIGN KEY (imagem_id) REFERENCES imagem (id)
) ENGINE=InnoDB DEFAULT CHARACTER SET=utf8mb4;
CREATE TABLE promocao (
id INT(11) NOT NULL AUTO_INCREMENT,
produto_id INT(11) NOT NULL,
preco NUMERIC(10, 2) NOT NULL,
validade DATE NULL,
obs VARCHAR(255) NOT NULL,
CONSTRAINT pk_promocao PRIMARY KEY (id),
CONSTRAINT fk_promocao_produto FOREIGN KEY (produto_id) REFERENCES produto (id)
) ENGINE=InnoDB DEFAULT CHARACTER SET=utf8mb4;
Subcategory and Category could be a single table and the images could be in another table.
– Valdeir Psr
In this case, category would have q be unique and the sub-categories can only repeat name if they are related to another category, as it would look?
– Robson H Rodrigues
You can use a column called
parent_id
. This column would take the value of the category ID (if it were a subcategory). If this column is 0 = parent category; if greater than 0 = child category. Example– Valdeir Psr
Amazing! Great solution! Thank you!
– Robson H Rodrigues