I have 2 mapped entities,
Box
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-To-Many, Unidirectional with Join Table association. Box can "store" candies, but Candy knows nothing about Box (where is).
Now I have page where I can make candy and there is 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 to Box can store only unique candies (by name), that means Box can store Candy objects with names "Choco" and "Orange" but can't "Mayonnaise" and "Mayonnaise"
When making candy i can't validate with UniqueEntity
constraint because the candy does not know about the box. I thought about Callback
validator for Box or create own Constraint but i think it's better to ask:
How should I do it?