当我坚持进入数据库时,我想跳过所有错误的条目。
代码看起来像这样:
...
processing a lot of data
...
foreach( $data as $d ){
$entity = new Entity();
$entity->setTitle($d['title']);
$entity->setDescription($d['description']);
$em->persist($entity);
}
$em->flush($entity);
现在我需要标题低于255个字符,这并不总是这样。我可以以某种方式忽略该实体并清除所有其他实体吗?
谢谢
答案 0 :(得分:2)
最好的方法是在持久化之前验证实体。
示例:
...
processing a lot of data
...
foreach( $data as $d ){
$entity = new Entity();
$entity->setTitle($d['title']);
$entity->setDescription($d['description']);
if($entity->isValid()) {
$em->persist($entity);
}
}
$em->flush();
另一种方法是逐个持久化实体并尝试/捕捉刷新,但是你的性能会下降
示例:
...
processing a lot of data
...
foreach( $data as $d ){
$entity = new Entity();
$entity->setTitle($d['title']);
$entity->setDescription($d['description']);
$em->persist($entity);
try{
$em->flush();
} catch(\Exception $e){
//error
}
$em->detach($entity);
}