【发布时间】:2012-07-31 16:41:33
【问题描述】:
我有一个与另一个实体有 OneToMany 关系的实体,当我坚持父实体时,我想确保子实体不包含重复项。
这是我一直在使用的类,discounts 集合不应包含给定客户的两个同名产品。
我有一个带有折扣集合的客户实体:
/**
* @ORM\Entity
*/
class Client {
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\Column(type="string", length=128, nullable="true")
*/
protected $name;
/**
* @ORM\OneToMany(targetEntity="Discount", mappedBy="client", cascade={"persist"}, orphanRemoval="true")
*/
protected $discounts;
}
/**
* @ORM\Entity
* @UniqueEntity(fields={"product", "client"}, message="You can't create two discounts for the same product")
*/
class Discount {
/**
* @ORM\Id
* @ORM\Column(type="string", length=128, nullable="true")
*/
protected $product;
/**
* @ORM\Id
* @ORM\ManyToOne(targetEntity="Client", inversedBy="discounts")
* @ORM\JoinColumn(name="client_id", referencedColumnName="id")
*/
protected $client;
/**
* @ORM\Column(type="decimal", scale=2)
*/
protected $percent;
}
如您所见,我尝试将UniqueEntity 用于 Discount 类,问题是验证器似乎只检查数据库上加载的内容(为空),所以当实体被持久化时,我得到一个“SQLSTATE [23000]:违反完整性约束”。
我已经检查了Collection 约束购买它似乎只处理字段集合,而不是实体。
还有 All 验证器,它允许您定义要应用于每个实体的约束,但不能应用于整个集合。
除了每次都写custom validator或Callback验证器之外,我需要知道整体是否存在实体集合约束,才能持久化到数据库。
【问题讨论】:
-
你的解决方案很好,我可以在来自 YAML 翻译文件的消息中添加翻译吗?
标签: validation symfony