为什么我的PersistentCollection为空?
我正在使用Symfony 3 Framework与Doctrine和MongoDB。为什么我的PersistentCollection为空?
我有两个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是空的事件,尽管信息在集合中存在?
我不知道你是如何创建的文档,但是这是我最好的拍摄:
Waypoint::$comments
没有被映射为反侧从而ODM预计引用的列表,可在waypoint.comments
领域在数据库。最有可能的是它不在那里(即你没有明确地向Waypoint
中的集合添加新的Comment
),这就是为什么当查询航点时看到空集合,但在查询注释时有结果。鉴于您在Comment
映射我想你忘了设置Waypoint::$comments
作为反方有inversedBy="comments"
:
/**
* @var ArrayCollection
* @MongoDB\ReferenceMany(targetDocument="Comment", mappedBy="waypoint")
*/
private $comments;
是的,我错过了'mappedBy =“waypoint”'部分因为它似乎导致了缺失的引用。谢谢,我只需要添加部分,现在它工作正常。 – KhorneHoly
“现在我从库中查询得到我的航点条目的一部分” - 请贴中提到的查询 – malarzm
@malarzm我编辑了这个问题 – KhorneHoly