duancifu6769 2016-11-14 15:07
浏览 43
已采纳

获取在Symfony3存储库中创建的MongoDB文档的ID

In my Symfony3 project, I do have some documents such as User, described below:

UserBundle\Document\User:
    repositoryClass: UserBundle\Repository\UserRepository
    fields:
        userId:
            id: true
        email:
            type: string
        firstName:
            type: string
        lastName:
            type: string

Some time, I want to create a user document through the user repository. Working around the createQueryBuilder(), I have built this method:

public function insert($email, $firstName, $lastName)
{
    $data = array('email' => $email,
        'firstName' => $firstName,
        'lastName' => $lastName,
    );

    /* Create query */

    $query = $this->createQueryBuilder();

    /* Add Data */

    $query
        ->insert()
        ->setNewObj($data);

    /* Return */

    $query
        ->getQuery()
        ->execute();

    return true;
}

Rather than returning true, I would like to return the Id of the document I have just created.

Looking for answers, I found this piece of code:

$this->getDocumentManager()->getConnection()->lastInsertId

Unfortunately, it is not returning what I am looking for:

object(MongoDB)[307]
  public 'w' => int 1
  public 'wtimeout' => int 10000

Thanks for your help !

EDIT:

Here is an updated code with the suggestion made in the accepted answer:

public function insert($email, $firstName, $lastName)
{
    $id = new MongoId();

    $data = array(
        '_id' => $id,
        'email' => $email,
        'firstName' => $firstName,
        'lastName' => $lastName,
    );

    /* Create query */

    $query = $this->createQueryBuilder();

    /* Add Data */

    $query
        ->insert()
        ->setNewObj($data);

    /* Return */

    $query
        ->getQuery()
        ->execute();

    return $id->__toString();
}
  • 写回答

2条回答 默认 最新

  • dsf487787 2016-11-23 14:48
    关注

    The easiest way to solve your problem is to generate the identifier upfront by calling new \MongoId(), adding it to data you're inserting (under _id key) and return known value. Also this is exactly what underlying MongoDB driver does behind the scenes when you're inserting a document without identifier set explicitly (see this doc example)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路