教义2关联未初始化 [英] doctrine2 association is not initialized

查看:15
本文介绍了教义2关联未初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类如下:

/** @Entity **/
class orgGroup{

    //id and stuff...

    /**
     * @Column(type="string")
     **/
    private $name;

    /**
     * @Column(type="string", nullable=true)
     **/
    private $description;

    /**
     * @ManyToOne(targetEntity="orgGroupType", inversedBy="_orgGroups")
     * @JoinColumn(name="_orgGroupType")
     **/

    private $_orgGroupType;

    //...
}

但是当我从我的数据库中加载这个对象时

But when i load this Object from my database via

$groups = $em->getRepository("orgGroup")->findAll();

我只是正确地获得了名称,但不是 _orgGroupType...而且我不知道为什么... OrgGroup 是 orgGroupType 的所有者,它只是一个对象而不是数组.我的网络服务总是说:

I just get the name correctly but not the _orgGroupType... and i dont know why... OrgGroup is the owner of orgGroupType and its just ONE object and not an array. My Webservice always just says:

{"error":[],"warning":[],"message":[],"data":[{"name":"AdministratorGroup","description":null,"_orgGroupType":{"__ isInitialized __":false}}]}

结果是:

"name":"AdministratorGroup",
"description":null,
"_orgGroupType":{"__ isInitialized __":false}

但应该是:

"name":"AdministratorGroup",
"description":"some description",
"_orgGroupType":{name:"test"}

所以有 2 个错误...我不知道为什么.数据库中的所有数据都设置正确.

So there are 2 errors... and I have no idea why. All the data is set correctly in the database.

有什么想法吗?

这是我的 orgGroupType -entity 缺少的代码

Here's the missing code of my orgGroupType -entity

/** @Entity **/
class orgGroupType {
    /**
     * @OneToMany(targetEntity="orgGroup", mappedBy="_orgGroupType")
     **/
    private $_orgGroups;

    public function __construct()
    {
        $this->_orgGroups = new ArrayCollection();
    }
}

推荐答案

在我看来,这就像一个延迟加载问题.如何将对象中的数据获取到 Webservice 答案中?

This looks to me like a lazy-loading-issue. How do you get the data from the object into the Webservice answer?

如果你不配置其他东西,Doctrine2 是延迟加载的,这意味着你的 $groups = $em->getRepository("orgGroup")->findAll(); 不会't 返回真正的 orgGroup 对象,但代理对象(教义文档).

Doctrine2 is lazy-loading if you don't configure something else, that means your $groups = $em->getRepository("orgGroup")->findAll(); won't return real orgGroup objects, but Proxy objects (Doctrine Documentation).

这意味着 $group 对象在您调用 $group->getDescription()$group- 之前不会有它的描述或 orgGroupType 值>getOrgGroupType()(然后 Doctrine 会自动加载它们),因此您需要在将数据写入 Web 服务的 JSON 响应之前执行此操作.如果您不使用 getter 方法而以某种方式遍历对象属性,它将无法工作.

That means a $group object won't have it's description or orgGroupType value until you call $group->getDescription() or $group->getOrgGroupType() (then Doctrine loads them automatically), so you need to do that before writing the data into the JSON-response for the webservice. It won't work if you somehow loop through the object properties without using the getter methods.

我希望这是问题所在:)

I hope that was the problem :)

这篇关于教义2关联未初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆