Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

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.



3.6k

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.



84.5k
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) {
        //...   
}

http://docs.phalconphp.com/en/latest/reference/models.html#isolated-transactions



3.6k

Thanks Phalcon