2013-12-23 27 views
0

我使用Symfony2的Doctrine Mongo db bundle。有關Doctrine Mongodb文檔中的字符串,int等數據類型的信息。但是,我找不到對象數據類型。如何使用Doctrine將對象添加到MongoDB中?

問題:如何使用Doctrine將對象添加到MongoDB中?如何在文檔類中定義(對象類型)?

回答

2

您只需定義與@MongoDB \文檔註釋類:

<?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); 
相關問題