Verify unique uniqueness for one-way, one-way, using the join table [Symfony2]

I have 2 objects mapped ,

Insert

class Box{ //[...] /** * @ORM\ManyToMany(targetEntity="Candy", cascade={"remove"}) * @ORM\OrderBy({"power" = "DESC"}) * @ORM\JoinTable(name="box_candies", * joinColumns={@ORM\JoinColumn(name="box_id", referencedColumnName="id")}, * inverseJoinColumns={@ORM\JoinColumn(name="candy_id", referencedColumnName="id", unique=true)} * ) */ private $candies; } 

And candy

 class Candy { /** * @var integer * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @var string * * @ORM\Column(name="name", type="string", length=255) */ private $name; //[...] } 

As you can see, this is One-way, one-way, with table join . Box can β€œstore” candy, but Candy knows nothing about Box (where it is).

Now I have a page where I can make candy , and there is a form and standard isValid() and after that:

 $box->addCandy($candy); $entity_manager->persist($candy); $entity_manager->persist($box); $entity_manager->flush(); 

Now where is my problem?

I would like Box to be able to store unique candies only (by name ), which means that Box can store Candy objects with the names "Choco" and "Orange" " , but cannot " mayonnaise "and" mayonnaise "

When creating candies, I cannot check with the UniqueEntity constraint because the candies are not aware of the gender. I was thinking of a Callback validator for Box or creating my own Constraint, but I think it's better to ask:

How can I do it?

+2
source share
1 answer

The answer is delayed, but it can help someone, so this is the solution I implemented:

In my case, I can create Candy only one place through the form, so finally I decided to create an additional special check for this case in my controller / service.

Simply put, I made the code by checking the name in my own way, and when it is not valid, just create a trow Error to prevent the creation. I want to emphasize that this is a slightly dirty solution, and also it does not scale, because you must always remember to add it to the right place if you create Candy in other places.

  // special unique name validation $candy_name = $form->get('name')->getData(); if($candy_name){ $found_candy = $box->getCandyByName($candy_name); if($found_candy){ $error = new FormError( $this->get('translator')->trans("candy.name.exist", array(), "validators") ); $form->get('name')->addError($error); } } 

In any case, it worked, but depending on your case, Callback may be the best solution or even a simple UniqueEntity restriction.

0
source

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


All Articles