Entity/User.php:
// ...
use DoctrineCommonCollectionsArrayCollection;
// ...
/**
* @var ArrayCollection
*
* @ORMOneToMany(targetEntity="Picture", mappedBy="user")
* @ORMOrderBy({"file" = "ASC"})
**/
private $pictures;
/**
* Constructor
*/
public function __construct()
{
$this->pictures = new DoctrineCommonCollectionsArrayCollection();
}
/**
* Add picture
*
* @param MyBundleEntityPicture $picture
*
* @return User
*/
public function addPicture(MyBundleEntityPicture $picture)
{
$this->pictures[] = $picture;
return $this;
}
/**
* Remove picture
*
* @param MyBundleEntityPicture $picture
*/
public function removePicture(MyBundleEntityPicture $picture)
{
$this->pictures->removeElement($picture);
}
/**
* Get pictures
*
* @return DoctrineCommonCollectionsCollection
*/
public function getPictures()
{
return $this->pictures;
}
// ...
实体/图片.php
// ...
/**
* @var ArrayCollection
*
* @ORMManyToOne(targetEntity="User", inversedBy="pictures")
* @ORMJoinColumn(name="user", referencedColumnName="id")
*/
private $user;
/**
* Set user
*
* @param MyBundleEntityUser $user
*
* @return Picture
*/
public function setUser(MyBundleEntityUser $user = null)
{
$this->user = $user;
return $this;
}
/**
* Get user
*
* @return MyBundleEntityUser
*/
public function getUser()
{
return $this->user;
}
// ...
控制器/图片控制器.php:
// ...
public function indexAction(Request $request)
{
return array(
'pictures' => $this->getUser()->getPictures(),
);
}
// ...
这是我转储->getPictures()的结果时Symfony的分析器输出的内容:
PersistentCollection {#292 ▼
-snapshot: []
-owner: User {#270 ▶}
-association: array:16 [ …16]
-em: EntityManager {#53 …11}
-backRefFieldName: "user"
-typeClass: ClassMetadata {#272 …}
-isDirty: false
#collection: ArrayCollection {#293 ▶}
#initialized: false
}
不知何故,集合没有初始化并且没有项目,尽管数据库中有一些......我在这里错过了什么?
将其添加到您的教义注释中,使其延迟加载相关实体;
@ORM\OneToMany(targetEntity="Picture", mappedBy="user",fetch="EAGER")