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 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料