我无法在控制器中持久存在多个实体。我只能保存最后一个。
我的代码:
$product = new Product();
$names = ['yellow', 'blue', 'red']; // save these to the table
foreach ($name as $name) {
$product->setName($name);
$em->persist($product);
// $em->flush(); // doesn't work either
}
$em->flush();
我正在使用Symfony 2.7
您必须在循环中创建一个新的Product。目前,它只接受了一种产品,并且不断更新。
$names = ['yellow', 'blue', 'red']; // save these to the table
foreach ($names as $name) {
$product = new Product();
$product->setName($name);
$em->persist($product);
}
$em->flush();
我创建了这个看起来不错的解决方案:
array_walk($arrayOfEntities, function ($entity) {
$entityManager->persist($entity);
});
使用克隆运算符(php5+)
$product = new Product();
$names = ['yellow', 'blue', 'red'];
foreach ($names as $name) {
$tmpProductObj = clone $product;
$em->persist($tmpProductObj);
}
$em->flush();
有关克隆对象的更多信息,请访问
您只创建了一个Object Product。显然,只有一个对象会被持久化到数据库中。此外,在顶部,您的变量被称为$Product
(大写P),而在循环中,它被称为$product
。
试试这个:
$NameList = array("yellow","blue","red"); // save these to the table
foreach($NameList as $name){
$product = new Product();
$product->setName($name);
$em->persist($Product);
//$em->flush(); // doesnot work either
}
$em->flush();
如果我想在设置其值后添加多个对象,我会在循环中使用克隆:
$application = new Application();
$application->setSomething($someting);
for ($i = 1; $i <= $request->get('number_of_applications'); $i++){
$applicationObj = clone $application;
$em->persist($applicationObj);
}
$em->flush();