原则 2 OneToOne 实体映射返回空实体
设置:
我有以下代码两个实体模型:
帐户,代表用户帐户并具有指向教室的外键。
<?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->find('Account',$id);
时,我正确地从数据库取回帐户,但 $account->classroom;
是一个空(非空)对象。经过一番尝试后,我尝试在执行之前添加以下命令:
$em->getRepository('Classroom')->findAll().
然后我执行了 $em->find('Account', $id );
并且帐户对象内的教室对象正确返回。
推测:
我认为从数据库加载和缓存实体的方式有问题,因为如果我在执行操作之前加载所有教室对象(或与帐户 I 关联的对象), find()
,那么一切都很好。
由于我是 PHP 和 Doctrine 的初学者,我寻求进一步的意见/帮助来解决这个问题。
The setup:
I have the following code two entity models:
Account, representing the user account and has a foreign key to classroom.
<?php
namespace models;
/**
* @Entity
*/
class Account
{
/**
* @Id @Column(type="integer")
* @GeneratedValue(strategy="AUTO")
*/
public $id;
/**
* @OneToOne(targetEntity="Classroom")
*/
public $classroom;
}
Classroom that represents the classroom a Student is enroled in.
<?php
namespace models;
/**
* @Entity
*/
class Classroom
{
/**
* @Id @Column(type="integer")
* @GeneratedValue(strategy="AUTO")
*/
public $id;
/**
* @Column(type="string")
*/
public $name;
}
The problem:
When I do $account = $em->find('Account',$id);
I correctly get the account back from the database, but the $account->classroom;
is an empty (not null) object. After experimenting a bit I tried adding the following command before the execution:
$em->getRepository('Classroom')->findAll().
Then I executed the $em->find('Account', $id );
and the classroom object inside the account object returned correctly.
Speculation:
I assume that there is something wrong with the way entities are loaded and cached from the database, because if I load all the classroom objects (or the one associated with the account I) before I do my find()
, then everything is fine.
As I'm beginner of PHP and Doctrine, I seek further opinions/help to solve that issue.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
来自 Doctrine 架构文档:
您的
$classroom
属性是public
,这可能就是与 Classroom 实体的关联未被延迟加载的原因。您应该将其更改为private
或protected
(我建议将所有实体属性设置为protected
,对于 各种原因)。如果这不起作用,您可以尝试将
OneToOne
关联的fetch
属性设置为 EAGER,即From the Doctrine Architecture Documentation:
Your
$classroom
property ispublic
, which is probably why the association with the Classroom entity is not being lazy-loaded. You should change it to beprivate
orprotected
(I recommend making all your Entity propertiesprotected
, for various reasons).If that doesn't work, you could try setting the
fetch
attribute of yourOneToOne
association to EAGER, i.e.