Nette - database INSERT - number of affected rows

398 Views Asked by At

I would like to find out the number of affected (inserted) rows after inserting into the table. I didn't figure out how to do it in the documentation. The update returns the number of affected rows. The insert returns Nette\Database\Table\ActiveRow How do I get it?

$affected = $context->table('author')->insert([
    [
        'name' => 'Sansa Stark',
        'born' => null
    ], [
        'name' => 'Arya Stark',
        'born' => null
    ]
]);
bdump($affected); //  Nette\Database\Table\ActiveRow - I need the number of inserted records
2

There are 2 best solutions below

1
On BEST ANSWER

Nette Database Explorer doesn't return count after insert(). It is not useful information as long as you can count data before insert by yourself.

$data = [...];
$count = count($data);
$context->table('author')->insert($data);

It works only with update and delete as is mentioned in documentation.

$count = $context->table('author')
    ->where('id', 10)
    ->delete();

It might be possible with getRowCount() over query in Nette Database Core

0
On

Nette Database Core is built upon PDO. Alas, the authors tend to create their own objects instead of extending PDO, which makes such elementary operations tedious:

// get Nette ResultSet object
$resultSet = $this->database->query("INSERT/UPDATE/DELETE...");

// get original PDOStatement object
$pdoStatement = $resultSet->getPdoStatement();

// get the affected rows from PDO object (instead of $resultSet->rowCount())
$pdoStatement->rowCount();

A word of warning for those considering Nette for production: There is no real documentation, only cook books and autogenerated PHPDoc which just prints names without any explanation.