2016-05-04 77 views
1

我无法在控制器内持久保存多个实体。我只能保存最后一个。在symfony2中保留多个实体

我的代码:

$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

回答

3

你必须创建循环内的新产品。 现在它只需要1个产品,并且不断更新。

$names = ['yellow', 'blue', 'red']; // save these to the table 

foreach ($names as $name) { 
    $product = new Product(); 
    $product->setName($name); 
    $em->persist($product); 
} 

$em->flush(); 
+1

喔,谢谢,现在的作品...很简单:) –

0

您只创建一个对象产品。 显然,只有一个对象会被保存到数据库中。 同样在顶部,变量名为$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();