ClanCats/Hydrahon

How can I get the last ID inserted?

Closed this issue · 1 comments

There is a way to execute the function like PDO::lastInsertId ?

Yes you can simply check the query type in your executor.

Example:

$connection = new PDO('mysql:host=localhost;dbname=my_database;charset=utf8', 'username', 'password');

// create a new mysql query builder
$h = new \ClanCats\Hydrahon\Builder('mysql', function($query, $queryString, $queryParameters) use($connection)
{
    $statement = $connection->prepare($queryString);
    $statement->execute($queryParameters);

    // when the query is fetchable return all results and let hydrahon do the rest
    // (there's no results to be fetched for an update-query for example)
    if ($query instanceof \ClanCats\Hydrahon\Query\Sql\FetchableInterface)
    {
        return $statement->fetchAll(\PDO::FETCH_ASSOC);
    }

    // Return the last insert ID if the query is an insert one.
    if ($query instanceof \ClanCats\Hydrahon\Query\Sql\Insert) 
    {
        return $pdo->lastInsertId();
    }
});

$id = $h->table('people')->insert([
    ['name' => 'John'],
    ['name' => 'Jack'],
])->execute();