Doctrine2 Insert and retrieve new insert ID

后端 未结 4 1684
轮回少年
轮回少年 2020-12-30 18:30

In Doctrine2 using some thing like:

$user = array(\'username\' => \'example\', \'passsword\' => \'changeme\');

$conn->insert(\'users\', $user);
         


        
4条回答
  •  孤城傲影
    2020-12-30 19:15

    One can use the Doctrine\DBAL\Connection::lastInsertId() method.

    It can be used with native queries as well as manually written inserts.

    Example case:

    $query = 'INSERT INTO blabla...';
    $connection->executeUpdate($query, $params);
    
    var_dump($connection->lastInsertId());
    

    If using the ORM, you can obtain an instance of the connection from the entity manager:

    $connection = $em->getConnection();
    

    Note:
    Aside from the technical details, I agree with @Layke for using an entity for your specific case.

提交回复
热议问题