【问题标题】:Doctrine 2 OneToOne entity mapping returns empty EntitiesDoctrine 2 OneToOne 实体映射返回空实体
【发布时间】:2011-08-06 16:55:39
【问题描述】:

设置:

我有以下代码两个实体模型:

Account,代表用户帐号,有一个外键到教室。

<?php
namespace models;

/**
 * @Entity
 */
class Account
{
    /**
     * @Id @Column(type="integer")
     * @GeneratedValue(strategy="AUTO")
     */
    public $id;

    /**
     * @OneToOne(targetEntity="Classroom")
     */
    public $classroom;
}

代表学生注册的教室的教室。

<?php
namespace models;

/**
 * @Entity
 */
class Classroom
{
    /**
     * @Id @Column(type="integer")
     * @GeneratedValue(strategy="AUTO")
     */
    public $id;

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

问题:

当我执行$account = $em-&gt;find('Account',$id); 时,我正确地从数据库中取回了帐户,但$account-&gt;classroom; 是一个空(非空)对象。经过一番试验后,我尝试在执行前添加以下命令:

$em->getRepository('Classroom')->findAll().

然后我执行了$em-&gt;find('Account', $id );,并且帐户对象中的教室对象正确返回。

推测:

我认为从数据库加载和缓存实体的方式有问题,因为如果我在执行find() 之前加载所有教室对象(或与我的帐户关联的对象),那么一切没问题。

由于我是 PHP 和 Doctrine 的初学者,我寻求进一步的意见/帮助来解决这个问题。

【问题讨论】:

    标签: orm doctrine mapping doctrine-orm


    【解决方案1】:

    来自Doctrine Architecture Documentation

    任何实体类的所有持久属性/字段都应始终为privateprotected,否则延迟加载可能无法按预期工作

    您的$classroom 属性是public,这可能是与Classroom 实体的关联没有被延迟加载的原因。您应该将其更改为 privateprotected(我建议将所有实体属性设置为 protected,用于 various reasons)。

    如果这不起作用,您可以尝试将 OneToOne 关联的 fetch 属性设置为 EAGER,即

    /**
     * @OneToOne(targetEntity="Classroom", fetch="EAGER")
     */
    protected $classroom;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-01-27
      • 2013-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多