XF 2.2 Insert multiple rows through a loop doesn't work

emiya

Member
Hi,
I want insert multiple arrays through a loop to my database. The foreach loop seems to work, but only one entry is saved to the database.

PHP:
$visitor = \XF::visitor();
$fooRequest= \XF::em()->create ('Foo\AddOn:Class1');
$fooRequest->bulkSet([
    'userid' => $visitor->user_id,
    'username' => $visitor->username,
    'title' => $package->title,
    'created' => $dateTime->format('Y-m-d H:i:s'),
    'planid' => $package->id
]);
$fooRequest->save();
$lastId = $fooRequest->get('id');
$codes = array_chunk($_POST['code'], 4);
$codeRequest = \XF::em()->create ('Foo\AddOn:Class2');
$i = 0;
foreach($codes as $code) {
    $i ++;
    $insertCode = implode("-", $code);
    $codeRequest->bulkSet([
        'payment_id' => $lastId,
        'code' => $insertCode,
        'amount' => $_POST['amount'.$i]
    ]);
    $codeRequest->save();
}

Isn't it possible to use ->bulkset() to insert multiple rows into the database through a loop?

EDIT:

I actually did this on this way:
PHP:
 \XF::db()->insert('xf_foo_table', [
     'payment_id' => $lastId,
     'code' => $insertCode,
     'amount' => $_POST['amount'.$i]
 ]);

But I'm wondering if there is a better solution for this?
 
Last edited:
The creation of the entity should be done each time within the loop.

Code:
$i = 0;
foreach($codes as $code) {
    $i ++;
    $insertCode = implode("-", $code);

    $codeRequest = \XF::em()->create ('Foo\AddOn:Class2');
    $codeRequest->bulkSet([
        'payment_id' => $lastId,
        'code' => $insertCode,
        'amount' => $_POST['amount'.$i]
    ]);
    $codeRequest->save();
}

At the moment you’re creating an entity, setting values on it and then overwriting the values on that one entity in each loop.
 
Top Bottom