0

我将 Doctrine Mongo db bundle 与 Symfony2 一起使用。Doctrine Mongodb 文档中有关 string、int 等数据类型的信息。但是,我找不到对象数据类型。

问题:如何使用 Doctrine 将对象添加到 MongoDB 中?如何在文档类中定义(对象类型)?

4

3 回答 3

2

您只需使用 @MongoDB\Document 注释定义一个类:

<?php

namespace Radsphere\MissionBundle\Document;
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
/**
 * @MongoDB\Document(
 *      collection="user_statistics",
 *      repositoryClass="Radsphere\MissionBundle\DocumentRepository\UserStatisticsRepository",
 *      indexes={
 *          @MongoDB\Index(keys={"user_profile_id"="asc"})
 *      }
 *  )
 */
 class UserStatistics
 {


 /**
  * @var \MongoId
  *
  * @MongoDB\Id(strategy="AUTO")
  */
 protected $id;
 /**
  * @var string
  *
  * @MongoDB\Field(name="user_profile_id", type="int")
  */
 protected $userProfileId;
 /**
  * @var integer
  *
  * @MongoDB\Field(name="total_missions", type="int")
  */
 protected $totalMissions;
 /**
  * @var \DateTime
  *
  * @MongoDB\Field(name="issued_date", type="date")
  */
  protected $issuedDate;

  /**
   *
   */
  public function __construct()
  {
     $this->issuedDate = new \DateTime();
  }

  /**
   * {@inheritDoc}
  */
  public function getId()
  {
     return $this->id;
  }

  /**
  * {@inheritDoc}
  */
  public function getIssuedDate()
  {
    return $this->issuedDate;
  }

  /**
   * {@inheritDoc}
  */
  public function setIssuedDate($issuedDate)
  {
     $this->issuedDate = $issuedDate;
  }

  /**
   * {@inheritDoc}
  */
  public function getTotalMissions()
  {
    return $this->totalMissions;
  }

  /**
   * {@inheritDoc}
  */
  public function setTotalMissions($totalMissions)
  {
    $this->totalMissions = $totalMissions;
  }

  /**
   * {@inheritDoc}
  */
  public function getUserProfileId()
  {
    return $this->userProfileId;
  }

  /**
   * {@inheritDoc}
  */
  public function setUserProfileId($userProfileId)
  {
    $this->userProfileId = $userProfileId;
  }

 }

然后使用文档管理器创建文档:

    $userStatisticsDocument = new UserStatistics();
    $userStatisticsDocument->setUserProfileId($userProfile->getId());

    $userStatisticsDocument->setTotalMissions($totalMissions);
    $userStatisticsDocument->setIssuedDate(new \DateTime('now'));
    $this->documentManager->persist($userStatisticsDocument);
    $this->documentManager->flush($userStatisticsDocument);
于 2013-12-23T15:30:57.043 回答
1

更好地阅读文档以获得完整的理解:

  1. Symfony 网站上的 Symfony2 DoctrineMongoDBBundle 页面。
  2. Doctrine MongoDB 实现文档页面。对于类型,看 这里
于 2013-12-23T20:07:29.907 回答
1

假设“对象”是指文档(mongodb)或哈希(javascript),或者换句话说,一个键值数组,然后在学说蒙戈文档中查看字段类型哈希。

/**
 * @Field(type="hash")
 */
protected $yourvariable;

http://docs.doctrine-project.org/projects/doctrine-mongodb-odm/en/latest/reference/annotations-reference.html

于 2013-12-23T15:13:29.430 回答