我有部分(父级)、语言(子级)和货币(子级)实体。它们的属性通常通过验证器进行验证,但我有问题如何检查用户是否想要删除与部分实体连接的货币或语言实体。 Symfony 抛出异常:
An exception occurred while executing 'DELETE FROM Language WHERE id = ?'
with params [5]: SQLSTATE[23000]: Integrity constraint violation: 1451
Cannot delete or update a parent row: a foreign key constraint fails
(`mywork`.`section`, CONSTRAINT `FK_E2CE437382F1BAF4` FOREIGN KEY
(`language_id`) REFERENCES `language` (`id`))
我想捕获这个异常并正常发送消息来说明所发生的情况。我知道我可以通过 try catch block 捕获这个错误,但在我看来这不是 Symfony 中的正确解决方案。而且我不知道如何从 Doctrine\DBAL\DBALException 获取错误代码。
我想找到类似于验证器的解决方案。如果属性的值不正确,消息将发送给用户(客户端)。例如:
My\WebBundle\Entity\Highlight:
properties:
abbreviation:
- NotBlank:
message: "The abbreviation must be not empty."
- Length:
max: 8
maxMessage: "Error value <strong>{{ value }}</strong> - The abbreviation can contain max {{ limit }} characters."
我对如何捕获唯一记录并为用户编写消息也有同样的问题。
最佳答案
使用Class Constraint Validator 这样在验证函数中:
// ...
if ($language->getSection() !== NULL) {
// If you're using the new 2.5 validation API (you probably are!)
$this->context->buildViolation($constraint->message)
->atPath('section')
->addViolation();
// If you're using the old 2.4 validation API
/*
$this->context->addViolationAt(
'section',
$constraint->message,
array(),
null
);
*/
}
与检查唯一约束的方式相同,但我认为更好的主意是使用 bild-in validator
编辑: 如果我没听错的话,你有像下面这样的 parent - child 。尝试使用 preRemove LifeCycleCallbacks
/**
* @ORM\Entity
* @ORM\HasLifecycleCallbacks()
*/
class Parent
{
/**
* @var ArrayCollection
*
* @ORM\OneToMany(targetEntity="Child", mappedBy="parent")
*/
private $children;
/**
* @ORM\PreRemove
*/
public function deleteAllChildren()
{
//prevent
foreach ($this->getChildren() as $child) {
$this->children->removeElement($child);
$child->setParent(NULL);
}
}
}
关于validation - Symfony 2, Doctrine 2 - 如何验证删除子父关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27971712/