我将Doctrine Mongo db bundle与Symfony2一起使用。有关 Doctrine Mongodb 文档中的字符串、int 等数据类型的信息。但是,我找不到对象数据类型。
问题:如何使用Doctrine将对象添加到MongoDB中?如何在文档类中定义(对象类型)?
您只需使用 @MongoDB\Document 注释定义一个类:
<?php
namespace RadsphereMissionBundleDocument;
use DoctrineODMMongoDBMappingAnnotations as MongoDB;
/**
* @MongoDBDocument(
* collection="user_statistics",
* repositoryClass="RadsphereMissionBundleDocumentRepositoryUserStatisticsRepository",
* indexes={
* @MongoDBIndex(keys={"user_profile_id"="asc"})
* }
* )
*/
class UserStatistics
{
/**
* @var MongoId
*
* @MongoDBId(strategy="AUTO")
*/
protected $id;
/**
* @var string
*
* @MongoDBField(name="user_profile_id", type="int")
*/
protected $userProfileId;
/**
* @var integer
*
* @MongoDBField(name="total_missions", type="int")
*/
protected $totalMissions;
/**
* @var DateTime
*
* @MongoDBField(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);
假设"对象"是指文档(mongodb)或哈希(javascript),或者换句话说,键值数组,那么请参阅doctrine-mongo文档中的字段类型哈希。
/**
* @Field(type="hash")
*/
protected $yourvariable;
http://docs.doctrine-project.org/projects/doctrine-mongodb-odm/en/latest/reference/annotations-reference.html
最好阅读文档以充分理解:
- Symfony网站上的Symfony2 DoctrineMongoDBBundle页面。
- Doctrine MongoDB实现文档页面。对于类型,请看这里