我想
在持久化数据库时跳过所有错误的条目。
代码如下所示:
...
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 个字符,这并不总是这样。我可以以某种方式忽略该实体并刷新所有其他实体吗?
谢谢
最好的方法是在持久之前验证实体。
例:
...
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);
}