我正在使用带有Doctrine和MongoDB的Symfony 3 Framework。
我有两个属于OneToMany关系的文档。
/**
* Class Waypoint
* @package AppBundle\Document
* @MongoDB\Document(collection="waypoints", repositoryClass="AppBundle\Repository\WaypointRepository")
*/
class Waypoint
{
/**
* @var int
*
* @MongoDB\Id(strategy="auto")
*/
private $id;
/**
* @var ArrayCollection
* @MongoDB\ReferenceMany(targetDocument="Comment", cascade={"delete"})
*/
private $comments;
}
**
* Class Comment
* @package AppBundle\Document
* @MongoDB\Document(collection="comments", repositoryClass="AppBundle\Repository\CommentRepository")
*/
class Comment
{
/**
* @var int
*
* @MongoDB\Id(strategy="auto")
*/
private $id;
/**
* @var Waypoint
*
* @MongoDB\ReferenceOne(targetDocument="Waypoint", inversedBy="comments")
* @Assert\NotBlank()
*/
private $waypoint;
}
现在我从存储库查询中获取了Waypoint
个条目的一部分,并希望用树枝显示它们。
/**
* WaypointRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class WaypointRepository extends DocumentRepository
{
public function getWaypointsForCruiseByPage(Cruise $cruise, $page)
{
$displayLimit = 10;
$amountToSkip = 0;
if ($page > 1)
{
$amountToSkip = ($page -1) * $displayLimit;
}
$qb = $this->createQueryBuilder()
->select()
->field('cruise')->equals($cruise)
->field('isAutoWaypoint')->equals(false)
->sort('date', -1)
->skip($amountToSkip)
->limit($displayLimit)
;
$qb
->addOr($qb->expr()->field('hasImage')->equals(true))
->addOr($qb->expr()->field('hasAudio')->equals(true))
->addOr($qb->expr()->field('description')->notEqual(''))
;
return $qb->getQuery()->toArray();
}
}
现在,我正在尝试{{ waypoint.comments.count }}
或{{ waypoint.comments|length }}
始终为0,即使我的MongoDB集合中有数据集。
如果我通过Waypoint的ID获得对CommentRepository的评论,我会得到预期的结果。
// returns the expected results
public function getAllCommentsForWaypoint(Waypoint $waypoint)
{
return $this->createQueryBuilder()
->select()
->field('waypoint')->equals($waypoint)
->getQuery()->toArray()
;
}
据我所知,映射很好,没有缺陷或错误。
为什么PersistentCollection为空,虽然信息集合中有信息?
答案 0 :(得分:1)
我不确定你是如何创建文档的,但这是我最好的镜头:
Waypoint::$comments
未映射为反面,因此ODM期望在数据库的waypoint.comments
字段中提供引用列表。很可能它不在那里(即你没有明确地向Comment
中的集合添加新的Waypoint
),这就是为什么你看到空的原因查询路标时的集合,但查询评论时会产生结果。鉴于您在inversedBy="comments"
映射中有Comment
,我认为您忘记将Waypoint::$comments
设置为反面:
/**
* @var ArrayCollection
* @MongoDB\ReferenceMany(targetDocument="Comment", mappedBy="waypoint")
*/
private $comments;