Symfony insert database entries while foreach loop

Viewed 48

My problem is, that symfony only inserts the last entry in the foreach loop and not all entries.

In my example, only Test 2 will be inserted.

My code: information: $_POST['title'] = Test, Test

$_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

1 Answers

when you call

$em->persist($product); it will store an ID into the $product entity and store it as a record in DB

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.

Related