We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

How to create many records to database in phalcon

I want to create 10 rerords to db at the same time, but I dont know how to code:

$mymodel->title = 'abc';
$mymodel->description = 'xyz';
$mymodel->create();

Thanks in advance.



5.3k

Maybe I use $mymodel= new Mymodel(); in loop.

But I can not rollback all records if there are something wrong when creating sixth record, etc.

Thanks.



98.9k
Accepted
answer

You can use a transaction:

$tx = $this->transactions->get();

try {
    $mymodel = new MyModel();
    $mymodel->setTransaction($tx)
    $mymodel->title = 'abc';
    $mymodel->description = 'xyz';
    if (!$mymodel->create()) {
        $tx->rollback();
    }
} catch(TransactionFailed $e) {
        //...   
}

https://docs.phalcon.io/en/latest/reference/models.html#isolated-transactions



5.3k

Thanks Phalcon