php Doctrine2 插入和检索新的插入 ID
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7172967/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Doctrine2 Insert and retrieve new insert ID
提问by NimmoNet
In Doctrine2 using some thing like:
在 Doctrine2 中使用类似的东西:
$user = array('username' => 'example', 'passsword' => 'changeme');
$conn->insert('users', $user);
How would I then get the last ID of the user I just inserted? If it is not possible to do this then how do you gen a id so that you can the following:
那么我如何获得我刚刚插入的用户的最后一个 ID?如果无法做到这一点,那么您如何生成 id 以便您可以执行以下操作:
$id = //something here.
$user = array('username' => 'example', 'passsword' => 'changeme', 'id' => $id);
$conn->insert('users', $user);
回答by Flask
If you are using the ORM
如果您使用的是 ORM
$em->persist($object);
$em->flush();
$object->getId();
if you are using the DBAL:
如果您使用的是 DBAL:
$conn->lastInsertId();
http://www.doctrine-project.org/api/dbal/2.5/class-Doctrine.DBAL.Connection.html#_lastInsertId
http://www.doctrine-project.org/api/dbal/2.5/class-Doctrine.DBAL.Connection.html#_lastInsertId
回答by Nikola Petkanski
One can use the Doctrine\DBAL\Connection::lastInsertId()
method.
可以使用该Doctrine\DBAL\Connection::lastInsertId()
方法。
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:
如果使用 ORM,则可以从实体管理器获取连接的实例:
$connection = $em->getConnection();
Note:
Aside from the technical details, I agree with @Layke for using an entity for your specific case.
注意:
除了技术细节之外,我同意 @Layke 为您的特定案例使用实体。
回答by Layke
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.
然后当你持久化你的对象时,实体管理器将填充你试图用 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.
但是,一些警告是,您显然不能使用复合键 post 来执行此操作,并且您显然必须刷新所有实体。因此,如果您分离一个与您尝试获取 ID 的持久化实体有关联的实体,那么您将无法检索该 ID。
Aside from that Flask's answer is bang on.
除了那个 Flask 的答案是爆炸。
$em->persist($object);
$em->flush();
$object->getId();
回答by Bramus
$conn->lastInsertId();
will get you the last inserted ID when only using Doctrine's DBAL (sans ORM).
$conn->lastInsertId();
仅使用 Doctrine 的 DBAL(无 ORM)时,将获得最后插入的 ID。