我正在使用symfony 3.1.10制作的项目。
我有三个实体
MyEntity 1-> n MyPivotEntity
MyPivotEntity n-> 1 MySuperInheritanceEntity
,我还有另一个实体MyInheritanceEntity,它从具有单表继承的MySuperInheritanceEntity继承
我以MyEntityType形式创建了MyPivotEntity的CollectionType字段,但是当我从控制器创建createForm时,我收到了一条内存超出消息,因为构建器为每个MySuperInheritanceEntity进行了数据库请求。我该如何预防?在这种情况下,我根本不需要MySuperInheritanceEntity信息,只需要MyPivotEntity字段
<?php
/**
* MyEntity
*
* @ORM\Table(name="my_entity")
* @ORM\Entity()
*/
class MyEntity {
/**
* @ORM\OneToMany(targetEntity="MyPivotEntity", mappedBy="myEntity", cascade={"persist"})
*/
private $myPivotEntity;
}
/**
* MyPivotEntity
*
* @ORM\Table(name="my_pivot_entity")
* @ORM\Entity()
*/
class MyPivotEntity {
/**
* @ORM\ManyToOne(targetEntity="MyEntity", inversedBy="myPivotEntity", cascade={"persist"})
*/
private $myEntity;
/**
* @ORM\ManyToOne(targetEntity="MySuperInheritanceEntity", inversedBy="myPivotEntity", cascade={"persist"})
*/
private $mySuperInheritanceEntity;
}
/**
* MySuperInheritanceEntity
*
* @ORM\Table(name="my_super_inheritance_entity")
* @ORM\Entity()
* @ORM\InheritanceType("SINGLE_TABLE")
*/
class MySuperInheritanceEntity {
/**
* @ORM\OneToMany(targetEntity="MyPivotEntity", mappedBy="mySuperInheritanceEntity")
*/
private $myPivotEntity;
}
/**
* MyInheritanceEntity
*
* @ORM\Table(name="my_inheritance_entity")
* @ORM\Entity()
*/
class MyInheritanceEntity extends MySuperInheritanceEntity {
}
class MyEntityType extends AbstractType
{
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('myPivotEntity', CollectionType::class, [
'entry_type' => MyPivotEntityType::class
]);
}
}
class MyPivotEntityType extends AbstractType
{
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('somField');
}
}
class MyController extends Controller {
/**
* @Post("/myEntity/update")
*/
public function postMyEntityUpdateAction(Request $request, MyEntity $myEntity) {
$form = $this->createForm(MyEntityType::class, $myEntity);
// here error 500 because of too mach memory
// caused by the MyPivotEntityType wich runs a request for each entry,
// trying to retrive all the information about MySuperInheritanceEntity and MyInheritanceEntity
// even if I don't need it at all
// because of the @ORM\InheritanceType("SINGLE_TABLE")
// deleting the inheritance solves the problem, but I need it
$form->handleRequest($request);
if ($form->isValid()) {
$this->getEm()->flush();
return ['success' => true];
}
$errors = (string) $form->getErrors(true, false);
throw new HttpException(400, $errors);
}
}
答案 0 :(得分:1)
文档says:
关于单表继承有一个一般的性能考虑:如果目标实体是多对一或一对一 关联是STI实体,出于性能考虑,它最好 是继承层次结构中的叶实体(即没有子类)。
还请记住:
为OneToMany关联属性名称使用复数名称:
class MyEntity {
/**
* @ORM\OneToMany(targetEntity="MyPivotEntity", mappedBy="myEntity", cascade={"persist"})
*/
private $myPivotEntities;
}
作为一种替代方法,您可能会完全忘记继承,并拥有复制了所有属性和关联的单独的(以前是子级的)实体。