The table ps_category_product
in PrestaShop has the following structure
# Obtained using SHOW CREATE TABLE `ps_category_product`
CREATE TABLE `ps_category_product` (
`id_category` int(10) unsigned NOT NULL,
`id_product` int(10) unsigned NOT NULL,
`position` int(10) unsigned NOT NULL DEFAULT '0',
KEY `category_product_index` (`id_category`,`id_product`),
KEY `id_product` (`id_product`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
For me is not very clear, but it seems that the fields id_category
and id_product
should be unique among the table, but for some reason MySQL allows me to insert duplicates:
mysql> select * from ps_category_product limit 10;
+-------------+------------+----------+
| id_category | id_product | position |
+-------------+------------+----------+
| 11 | 1 | 1 |
| 11 | 2 | 1 |
| 11 | 3 | 1 |
| 11 | 4 | 1 |
| 11 | 5 | 1 |
| 11 | 6 | 1 |
| 11 | 7 | 1 |
| 11 | 8 | 1 |
| 11 | 9 | 1 |
| 11 | 10 | 1 |
+-------------+------------+----------+
10 rows in set (0.00 sec)
mysql> INSERT INTO `ps_category_product` VALUES(11, 1, 1);
Query OK, 1 row affected (0.05 sec)
How can I prevent this from happening?
It was a bug in prestashop. Take a look at http://forge.prestashop.com/browse/PSCFI-4397
Specifying KEY
will not enforce a unique constraint unless you specify UNIQUE KEY
or PRIMARY KEY
.
Try recreating the table using the following DDL:
CREATE TABLE `ps_category_product` (
`id_category` int(10) unsigned NOT NULL,
`id_product` int(10) unsigned NOT NULL,
`position` int(10) unsigned NOT NULL DEFAULT '0',
UNIQUE KEY `category_product_index` (`id_category`,`id_product`),
KEY `id_product` (`id_product`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
That should do the trick.
Have a look at the MySQL CREATE TABLE syntax for more info.
The constraint should be imposed via the admin interface and underlying object code, so you shouldn't ever have a situation where there are duplicates, although it would be easy enough to write a cron job to remove any that did occur.
You could force this unique, but that doesn't solve the fundamental problem as to why this might happen.... I honestly don't see what the issue is that you're trying to solve? If you're importing products yourself, then you should use the object interface rather than writing to these tables directly, otherwise, yes - weird things might happen.