database Symfony2:获取持久化对象的 id
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/12952331/
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
Symfony2: get the id of the persisted object
提问by Milo?
I have two entity: User and Person.
我有两个实体:用户和个人。
In the entity User I need the id of the associated person: user_id.
在实体用户中,我需要关联人员的 ID:user_id。
When I am creating a new user, I have to create first the person and then the user. In the user, I have to put the id of the corresponding person and for that I need to get the id of the persisted object person which is an auto increment.
当我创建一个新用户时,我必须先创建人,然后再创建用户。在用户中,我必须输入相应人员的 id,为此我需要获取持久化对象人员的 id,这是一个自动增量。
Is it possible to get the id of the object after:
是否可以在以下之后获取对象的 id:
$em->persist($person);
$em->flush();
And how can I do this?
我该怎么做?
The alternative is to search the biggest id it the table Person and take this one but I think there should be a better and easier method to get the id of the persisted object.
另一种方法是在表 Person 中搜索最大的 id 并采用这个,但我认为应该有一种更好、更简单的方法来获取持久对象的 id。
In php for example, when I execute
例如在 php 中,当我执行
$articleID = $_DB->queryRaw((....);
I am getting the id like that.
我得到这样的id。
回答by Habibillah
Symfony2 with Doctrineas default ORM will automatically generate an ID after data stored in database. So you can call the ID by ->getId()
Symfony2 以 Doctrine作为默认 ORM 会在数据存储到数据库后自动生成一个 ID。所以你可以通过以下方式调用ID->getId()
$id = $person->getId();

