Unique identifiers in symfony2 join table

I have two products and categories of objects, I have successfully created many, many b / w relationships, as a result a new table was created that looks like this:

┌────────────────┐ ┌───────────────────┐ ┌────────────────┐ | products | | product_categories| | categories | ├────────────────┤ ├───────────────────┤ ├────────────────┤ | id# ├---------┤ product_id | ┌----┤ id# | | -- | | cat_id ├----┘ | -- | | -- | | | | | └────────────────┘ └───────────────────┘ └────────────────┘ 

Category

  /** * @ORM\ManyToMany(targetEntity="Products", mappedBy="category") */ protected $product; 

Products

  /** * @ORM\ManyToMany(targetEntity="categories", inversedBy="product") * @ORM\JoinTable(name="product_categories", * joinColumns={@ORM\JoinColumn(name="product_id", referencedColumnName="id")}, * inverseJoinColumns={@ORM\JoinColumn(name="cat_id", referencedColumnName="id")} * ) **/ protected $category; 

Now I want the product and cat_id to be unique in the product_categories table. How can I do that?

+2
source share
1 answer

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; /** * @ORM\Entity * (...) * @UniqueEntity(fields={"product_id", "cat_id"}) */ 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 --force 

(with most of the above commands, you can also add the --dump-sql argument, which only displays sql instead of modifying your database)

+6
source

Source: https://habr.com/ru/post/1240033/


All Articles