我有两份文件。我试图找到与特定人相关的所有论文。这些文档正在保存在他们的集合中,并且正在创建从Person
到Paper
的引用,但不是相反。
/** @ODM\Document */
class Paper
{
/**
* @ODM\Id
*/
protected $id;
/** @ODM\ReferenceOne(targetDocument="Person", cascade={"all"}, mappedBy="papers") */
protected $person;
public function __get($property) {
return $this->$property;
}
public function __set($property, $value) {
$this->$property = $value;
}
public function toArray() {
return get_object_vars($this);
}
}
/** @ODM\Document */
class Person
{
/**
* @ODM\Id
*/
protected $id;
/** @ODM\ReferenceMany(targetDocument="Paper", cascade={"all"}, inversedBy="person") */
protected $papers;
public function __get($property) {
return $this->$property;
}
public function __set($property, $value) {
$this->$property = $value;
}
public function toArray() {
return get_object_vars($this);
}
}
创建一个新的双向参考
$person = $dm->getRespository('Person')->find($person_id);
$paper = new Paper();
$person->papers->add($paper);
$dm->persist($person);
$dm->flush();
稍后在代码中,此查询返回0结果;不应该归还指定人士写的论文吗?
$papers = $dm->createQueryBuilder('Paper')
->field('person.$id')->equals(new \MongoId($person_id_as_string))
->getQuery()->execute();
答案 0 :(得分:2)
如果Paper :: person用“mappedBy”注释,则意味着Paper不是“拥有者”,并且学说不会持续对Paper :: person进行任何更改。
要使您的查询有效,请将Paper设为拥有方,以便Paper存储对Person的引用。
/** @ODM\Document */
class Person
{
/** @ODM\ReferenceMany(targetDocument="Paper", mappedBy="person") */
protected $papers;
}
/** @ODM\Document */
class Paper
{
/** @ODM\ReferenceOne(targetDocument="Person", inversedBy="papers") */
protected $person;
}
创建论文并坚持引用人:
$person = $dm->getRespository('Person')->find($person_id);
$paper = new Paper();
$paper->person = $person;
$dm->persist($paper);
$dm->flush();
以$ person查询论文:
$papers = $dm->createQueryBuilder('Paper')
->field('person')->references($person)
->getQuery()->execute();