Doctrine2 Insert and retrieve new insert ID

后端 未结 4 1679
轮回少年
轮回少年 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:09

    $conn->lastInsertId();will get you the last inserted ID when only using Doctrine's DBAL (sans ORM).

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-30 19:19

    Providing that your Entity which are you are trying to set has

       /**
         * @Id @Column(type="integer")
         * @GeneratedValue
         */
        private $id;
    

    Then when you persist your object, the entity manager will populate the Entity which you are trying to persist with the ID.

    Some caveats however, is that you can't do this with composite keys post obviously, and you obviously have to flush all Entities. So if you detach an Entity which has an association to the persisted entity that you are trying to get the ID for, then you won't be able to retrieve the ID.

    Aside from that Flask's answer is bang on.

    $em->persist($object);
    $em->flush();
    $object->getId();
    
    0 讨论(0)
  • 2020-12-30 19:22

    If you are using the ORM

    $em->persist($object);
    $em->flush();
    $object->getId();
    

    if you are using the DBAL:

    $conn->lastInsertId();
    

    http://www.doctrine-project.org/api/dbal/2.5/class-Doctrine.DBAL.Connection.html#_lastInsertId

    0 讨论(0)
提交回复
热议问题