[英]Symfony Form EntityType without Hydration
我正在建立一个带有很多嵌套对象的网站。 但随着数据库的增长,慢慢地,但肯定地,Doctrine关联开始真正显示出来。 我遇到的最重要的问题之一是,我需要创建下拉菜单,以便用户可以关联其中一些实体。 下面的代码是我用来生成表单的FormType之一的一部分。
$builder
->add('sidebarcontent')
->add('publicAgenda')
->add('assets')
->add('structure')
->add('history')
->add('emblem')
->add('demonym')
->add('type', EntityType::Class, array(
'class' => 'ContentBundle\Entity\OrganizationType',
'choice_label' => 'name',
'empty_data' => '',
'required' => false,
'query_builder' =>function (EntityRepository $er) use ( $world ) {
return $er->createQueryBuilder('c')
->orderBy('c.name', 'ASC');
}))
->add('geographicLocation', EntityType::Class, array(
'class' => 'ContentBundle\Entity\Location',
'choice_label' => 'title',
'empty_data' => '',
'required' => false,
'query_builder' =>function (EntityRepository $er) use ( $world ) {
return $er->createQueryBuilder('c')
->where('c.world = ?1')
->setParameter(1, $world)
->andWhere('c.state != ?2')
->setParameter(2, 'archived')
->orderBy('c.title', 'ASC');
}
))
->add('parent', EntityType::Class, array(
'class' => 'ContentBundle\Entity\Organization',
'choice_label' => 'title',
'empty_data' => '',
'required' => false,
'query_builder' =>function (EntityRepository $er) use ( $world ) {
return $er->createQueryBuilder('c')
->where('c.world = ?1')
->setParameter(1, $world)
->andWhere('c.state != ?2')
->setParameter(2, 'archived')
->orderBy('c.title', 'ASC');
}
))
->add('ethnicities', EntityType::Class, array(
'class' => 'ContentBundle\Entity\Ethnicity',
'choice_label' => 'title',
'empty_data' => '',
'multiple' => true,
'expanded' => true,
'required' => false,
'query_builder' =>function (EntityRepository $er) use ( $world ) {
return $er->createQueryBuilder('c')
->where('c.world = ?1')
->setParameter(1, $world)
->andWhere('c.state != ?2')
->setParameter(2, 'archived')
->orderBy('c.title', 'ASC');
}
));
有没有办法将这些实体提取到最低限度(uuid,标题),而不是水合它们? 我什至不确定这是否是正确的问题。 我只是想减少现在的加载时间。
EntityType表单字段是必需的实体对象,您不能仅选择必需的字段,因为否则,它将不知道在实体关系中要保留的内容。
如果确实只需要提取某些字段,则必须使用ChoiceType字段。 但是请记住,在持久化实体时,将需要具有相关实体的对象。
作为另一种选择,您也可以尝试将choices参数与找到的查询结果一起使用,这样您就可以缓存查询和/或查询结果。
例如:用表格中的choices参数替换query_builder参数。
$choices = $this->createQueryBuilder('c')
->where('c.world = ?1')
->setParameter(1, $world)
->andWhere('c.state != ?2')
->setParameter(2, 'archived')
->orderBy('c.title', 'ASC');
->getQuery()
->useQueryCache(true)
->useResultCache(true, 3600) // this will cache most common results for a while.
->execute();
然后该领域如下。
->add('geographicLocation', EntityType::Class, array(
'class' => 'ContentBundle\Entity\Location',
'choice_label' => 'title',
'empty_data' => '',
'required' => false,
'choices' => $choices
))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.