我有两个具有 oneToMany 关系的实体:
发布实体:
...
oneToMany:
images:
mappedBy: post
targetEntity: Shop\Bundle\ManagementBundle\Entity\Image
图像实体:
...
manyToOne:
post:
targetEntity: Shop\Bundle\ManagementBundle\Entity\Post
inversedBy: images
joinColumn:
onDelete: cascade
使用 Post
的 $entity
实例,当我执行 $entity->getImages()
时,我收到类似以下内容:
object(Doctrine\ORM\PersistentCollection)[65]
private 'snapshot' =>
array (size=0)
empty
private 'owner' =>
object(Acme\Bundle\ImageUpBundle\Entity\Post)[54]
private 'id' => int 41
private 'title' => string 'kbd' (length=3)
private 'images' =>
&object(Doctrine\ORM\PersistentCollection)[65]
private 'association' =>
array (size=15)
'fieldName' => string 'images' (length=6)
'targetEntity' => string 'Shop\Bundle\ManagementBundle\Entity\Image' (length=38)
'mappedBy' => string 'post' (length=4)
'type' => int 4
'inversedBy' => null
'isOwningSide' => boolean false
'sourceEntity' => string 'Shop\Bundle\ManagementBundle\Entity\Post' (length=37)
'fetch' => int 2
'cascade' =>
array (size=0)
empty
'isCascadeRemove' => boolean false
'isCascadePersist' => boolean false
'isCascadeRefresh' => boolean false
'isCascadeMerge' => boolean false
'isCascadeDetach' => boolean false
'orphanRemoval' => boolean false
private 'em' =>
....
但现在我不幸得到null
。
我确实尽了最大努力找出可能导致此类问题的原因。非常感谢您的帮助。
编辑:
给定一个整数 $id,我使用以下方法获取 Post 实体:
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('ShopManagementBundle:Post')->find($id);
我成功获取了 Post 实体的所有属性(除了 images
之外)。
最佳答案
以下是解决我的问题的方法:
1-我在配置文件中的一个 oneToMany
参数下收集了所有一对多关联。换句话说,而不是:
oneToMany:
images:
targetEntity....
....
oneToMany:
messages:
targerEntity...
....
我会:
oneToMany:
images:
targerEntity...
....
messages:
targerEntity...
....
- 我再次使用
app/console doc:gen:entities
生成了实体,使唯一的一个构造函数构造了两个ArrayCollection
。
/** * Constructor */ public function __construct() { $this->messages = new \Doctrine\Common\Collections\ArrayCollection(); $this->images = new \Doctrine\Common\Collections\ArrayCollection(); }
现在,当我调用 $em->getRepository('ShopManagementBundle:Post)->find($id)
时,我将子实体 (Images
) 附加到我的当数据库中存在具体记录且不为 Null 时,父实体 (Post
)。当我使用 new Post()
实例化一个新实体时,我有空的 ArrayCollection 而不是 Null。
我知道这个答案缺乏编程逻辑,看起来很武断,但我写它是为了分享,以防有人突然遇到这个问题(就像我一样)。我希望它有帮助。
关于symfony - 获取子实体返回 null 而不是 arrayCollection 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34725409/