Proxy 学说2。如何从代理中强制实体

Proxy 学说2。如何从代理中强制实体,proxy,doctrine-orm,lazy-loading,Proxy,Doctrine Orm,Lazy Loading,我有3个实体: /** * @ORM\Entity * @ORM\Table(name="table_a") */ class A { /** * @ORM\Id * @ORM\Column(type="integer") * @ORM\GeneratedValue */ protected $id; /** * ORM\OneToMany(targetEntity="B", mappedBy="entityA") */

我有3个实体:

/**
 * @ORM\Entity
 * @ORM\Table(name="table_a")
 */

class A
{
   /**
    * @ORM\Id
    * @ORM\Column(type="integer")
    * @ORM\GeneratedValue
    */
   protected $id;

   /**
    * ORM\OneToMany(targetEntity="B", mappedBy="entityA")
    */
   protected $entitiesB;

   /**
    * ORM\OneToMany(targetEntity="C", mappedBy="entityA")
    */
   protected $entitiesC;

   /**
    * @ORM\Column(type="string")
    */
   protected $name;
}


/**
 * @ORM\Entity
 * @ORM\Table(name="table_b")
 */

class B
{
   /**
    * @ORM\Id
    * @ORM\Column(type="integer")
    * @ORM\GeneratedValue
    */
   protected $id;

   /**
    * ORM\ManyToOne(targetEntity="A", inversedBy="entitiesB")
    */
   protected $entityA;

   /**
    * @ORM\Column(type="date")
    */
   protected $date;
}


/**
 * @ORM\Entity
 * @ORM\Table(name="table_c")
 */

class C
{
   /**
    * @ORM\Id
    * @ORM\Column(type="integer")
    * @ORM\GeneratedValue
    */
   protected $id;

   /**
    * ORM\ManyToOne(targetEntity="A", inversedBy="entitiesC")
    */
   protected $entityA;

   /**
    * @ORM\Column(type="string")
    */
   protected $description;
}
我有以下情况:

$eB = $repositoryB->find(1);
$eA = $eB->getEntityA(); // $eA will be a proxy
$eC = new C();
$eC->setDescription('XXXXXXXXXX')
   ->setEntityA($eA);
这将生成一个错误,因为$eA是代理而不是实体。即使我尝试:

$eB = $repositoryB->find(1);
$eA = $repositoryA->find(1);
$eC = new C();
$eC->setDescription('XXXXXXXXXX')
   ->setEntityA($eA);
仍然会出现错误,因为一旦获取了B实体,它将自动获取实体的代理。当您尝试获取与代理具有相同标识符的实体时,该原则将从标识映射返回代理对象,因为不能有两个对象—一个代理和一个实体用于相同的db记录


那么,有没有办法强制从其代理检索实体?或者通过id而不是实体来设置关联的另一种方法?

您编写的代码应该可以工作,请发布您正在讨论的相关错误。我没有发布错误,因为它会让人困惑,并且与问题相关。错误如下:致命错误:未捕获异常“条令\ORM\ORMInvalidArgumentException”,消息为“通过关系“AentitiesB”找到了一个新实体,该关系未配置为级联实体的持久化操作:。要解决此问题,请在此未知实体上显式调用EntityManagerpersist,或在映射中配置cascade persist此关联,例如@Manytone..,cascade={persist}。在第336行的\library\Zend\Controller\Plugin\Broker.php中,$eA是代理而不是实体。如果我执行$eA=$repositoryA->findxx,其中xx是与代理类中的标识符不同的标识符,它将是一个实体,代码将正常工作。问题是我不能为同一条记录设置两个对象。我还尝试过通过查询生成器(如SELECT b,a FROM b JOIN b.entityA a,其中b.id=1)获取$eB,但它仍然给我提供了一个proxyLooks,比如EntitiesB附加到entityA的错误。但在您的示例中,EntityA以另一种方式附加到其他实体。你们有定制的getter和setter吗?你的脸红是什么样子的?首先非常感谢你的回复。我发现了问题所在。读完后,我意识到问题一定出在别的地方。所以我再次开始检查我的代码,发现在我的entity C类中,在setEntityA函数中有一个拼写错误的变量。由于这个原则,我抛出了一个错误,使我的ZF从我的操作中跳过了代码,并且因为在postDispach函数中,我有flush函数,这就是我得到错误消息的原因。