我是symfony的新手,并使用mongodb作为数据库创建项目。我正在使用嵌入式文档来实现多级数据库。以下是我正在使用的两个文档文件:
文档:
namespace AppBundle\Document;
/**
* @MongoDB\Document()
*/
class State
{
/**
* @MongoDB\Id()
*/
protected $id;
/**
* @MongoDB\Field(type="string")
*/
protected $name;
/**
* @MongoDB\Field(type="string")
*/
protected $code;
/**
* @MongoDB\EmbedMany(targetDocument="City")
*/
protected $cities = array();
/**
* State constructor.
*/
public function __construct()
{
$this->cities = new ArrayCollection();
}
/**
* @return mixed
*/
public function getId()
{
return $this->id;
}
/**
* @param mixed $id
*/
public function setId($id)
{
$this->id = $id;
}
/**
* @return mixed
*/
public function getName()
{
return $this->name;
}
/**
* @param mixed $name
*/
public function setName($name)
{
$this->name = $name;
}
/**
* @return mixed
*/
public function getCode()
{
return $this->code;
}
/**
* @param mixed $code
*/
public function setCode($code)
{
$this->code = $code;
}
/**
* @return City[]
*/
public function getCities()
{
return $this->cities;
}
/**
* @param City $city
*/
public function addCities(City $city)
{
$this->cities[] = $city;
}
}
/**
* @MongoDB\EmbeddedDocument()
*/
class City
{
/**
* @MongoDB\Id
*/
protected $id;
/**
* @MongoDB\Field(type="string")
*/
protected $name;
/**
* @return mixed
*/
public function getId()
{
return $this->id;
}
/**
* @param mixed $id
*/
public function setId($id)
{
$this->id = $id;
}
/**
* @return mixed
*/
public function getName()
{
return $this->name;
}
/**
* @param mixed $name
*/
public function setName($name)
{
$this->name = $name;
}
}
我能够将数据添加到数据库并预览下面显示的内容:
{
"_id" : ObjectId("59783f79d6faef0dc13cc8ce"),
"name" : "New South Wales",
"code" : "NSW",
"cities" : [
{
"_id" : ObjectId("59783f79d6faef0dc13cc8cf"),
"name" : "Sydney"
}
]
}
现在我正在使用方法" find()"用它的id:
$city = $this->get('doctrine_mongodb')
->getManager()
->getRepository('AppBundle:City')
->find("59783f79d6faef0dc13cc8cf");
所以,问题在于:
我在$ city收到 null 。我怎样才能得到像城市一样的城市细节?
答案 0 :(得分:1)
您已将City
映射为嵌入式文档,因此在没有其父文档的情况下无法存在。获取它的唯一方法是获取State
,然后迭代$state->getCities()
。如果您需要查询城市,则需要引用,因此City
将成为一个具有Mongo可以扫描的集合的第一类文档。