If you specify your many-to-many relationship implicitly, for example, via an annotation ( @ManyToMany ), Doctrine will create a composite primary key consisting of both fields: product_id and cat_id, so you have a guarantee that it will be unique.
If you specify your many-to-many associations explicitly through an optional object (say, ProductCategories ), you can simply add a UniqueEntity constraint.
Uniqueness Restriction Documentation
An example with annotations:
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity; class ProductCategories {
change
Also, make sure you create your database correctly. You should use Doctrine commands to do this (do not do it manually!):
php -f ./app/console doctrine:database:drop php -f ./app/console doctrine:database:create php -f ./app/console doctrine:schema:create
Thus, based on your objects, Doctrine will create the appropriate db schema. If you change something in the future (in your entities), you can simply update your schema:
php -f ./app/console doctrine:schema:update
(with most of the above commands, you can also add the --dump-sql argument, which only displays sql instead of modifying your database)
source share