In a virtual store panel that I am building the products have relationships by color and size, where each product color has a size.
This is a part of my database for a better understanding of the problem: link
When the user wants to associate the colors with a product in the panel it is forwarded to a page with all the colors (checkbox list) and in it he selects the colors and sends the form to php that processes with the following script :
Note: $database
is an instance of DBAL Doctrine
$checking = [];
$colors = (array) $_POST['colors'];
$ids = [];
foreach($colors as $color) if(is_numeric($color)) $ids[]=$color;
$emptyTableQuery = $database->createQueryBuilder();
$emptyTableQuery -> delete('product_colors')
-> where('id_product = :idProduct AND id_color NOT IN (:ids)')
-> setParameters([':idProduct'=>$id,':ids'=>implode(',',$ids)]);
$emptyTable = $emptyTableQuery->execute();
foreach($colors as $color)
$checking[] = $database->insert(
'product_colors',
[
'id_product'=> $id,
'id_color'=> $color
],
['id_product'=>\PDO::PARAM_INT,'id_color'=>\PDO::PARAM_INT]
);
When a new product is inserted the code works perfectly, however, when the colors of the product are updated the colors already existing in the database are duplicated ...
Before the current code ALL colors were removed from the table, or it was completely clean, which resulted in a problem greater: there is a third relation with the table called 'sizes_by_product_color' where sizes are stored for each color and the respective stocks, that is, if I deleted everything too these data were lost and the customer would have to register all sizes for colors, before existing, again ...
This is part of my database for a better understanding of the problem: link
How could I solve my problem in a practical way? is there a solution for SQL or will I have to do a select to do the check in PHP?