简体   繁体   English

Symfony 在 foreach 循环时插入数据库条目

[英]Symfony insert database entries while foreach loop

My problem is, that symfony only inserts the last entry in the foreach loop and not all entries.我的问题是,symfony 仅在 foreach 循环中插入最后一个条目,而不是所有条目。

In my example, only Test 2 will be inserted.在我的示例中,将仅插入测试 2。

My code: information: $_POST['title'] = Test, Test我的代码:信息:$_POST['title'] = Test, Test

$_POST['number'] = 1, 2 $_POST['number'] = 1, 2

$titles = $_POST['title'] ?? [];
$numbers = $_POST['number'] ?? [];

    foreach ($titles as $key => $title) {
        $product->setNumber($numbers[$key]);
        dump($numbers[$key]);
        $product->setTitle($title);
        dump($title);
        $em->persist($product);
    }
    $em->flush();

Screenshot of my dump:我的转储截图:

Screenshot of dump转储截图

when you call你打电话时

$em->persist($product); it will store an ID into the $product entity and store it as a record in DB它会将 ID 存储到$product实体中,并将其作为记录存储在数据库中

if you den change the title and store again, it will look at the $product entity and see "OH THERE IS AN ID, SO HE WANTS TO DO UPDATE" so $em stores the title for the ID that is set in $product on your first loop.如果您更改标题并再次存储,它将查看$product实体并看到“哦,有一个 ID,所以他想要更新”,因此$em存储在$product on 中设置的 ID 的标题你的第一个循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM