问题描述
我正在尝试创建一个表单,该表单的数据类型为集合类型,具体取决于要登录的用户。我正在。
I'm trying to create a form with data in collection type depending on the user being logged. I'm following this chapter of the Symfony cookbook.
当 query_builder
选项是一个从我从DQL获取数据的闭包时,一切工作正常。由于需要从代码的不同位置获取数据,因此,我希望在Repository类中定义查询。
Everything works fine when the query_builder
option is a closure where I get my data from DQL. As the data need to be fetched from different location in code, I would prefer to define the query in the Repository class.
这是我的存储库中的函数:
Here is the function in my repository :
public function findOwnedBy($user) {
$query = $this->getEntityManager()->createQuery("SELECT l FROM MyBundle:Article a JOIN a.owndBy u WHERE u.id = :userId");
$query->setParameters(array("userId"=>$user->getId()));
return $query->getResult();
}
此函数在Controller中调用并返回Article数组时有效。这是symfony doc的摘要:
This function works when called in a Controller and return an array of Article. Here is a snippet of the symfony doc :
$formOptions = array(
'class' => 'Acme\DemoBundle\Entity\User',
'multiple' => false,
'expanded' => false,
'property' => 'fullName',
'query_builder' => function(EntityRepository $er) use ($user) {
// build a custom query, or call a method on your repository (even better!)
},
);
当我在query_builder中调用存储库函数时,出现错误: Doctrine\ORM\QueryBuilder类型的预期参数,给出了数组
,我可以理解,因为我的存储库返回的是实体数组,而不是QueryBuilder。
When I put a call to my Repository function in the query_builder, I get an error : Expected argument of type "Doctrine\ORM\QueryBuilder", "array" given
, which I can understand because my Repository returns an array of Entity, not a QueryBuilder.
我不想复制代码并在表单中创建一个新的QueryBuilder。使用存储库中的查询的最佳实践是什么?我当时在考虑在存储库中有两个功能,一个返回数组,另一个返回QueryBuilder,但是Symfony文档中的注释 或在存储库上调用方法(甚至更好!)让我认为这种情况有更好的方法。
I don't want to duplicate code and create a new QueryBuilder in the Form. What is the best practice to use the query from the Repository ? I was thinking of having two function in the repository, one returning an array and the other returning the QueryBuilder, but the comment in Symfony doc "or call a method on your repository (even better!)" let me think there's better way for this case.
推荐答案
应该很容易。请执行以下操作:
It should be easy. Do the following:
public function queryOwnedBy($user) {
$query = $this->createQueryBuilder('a')
->from('MyBundle:Article', 'a')
->innerJoin('a.owndBy', 'u')
->where('u.id = :id')
->setParameter('id', $user->getId());
return $query;
}
public function findOwnedBy($user) {
return $this->queryOwnedBy($user)
->getQuery()
->getResult();
}
然后在表单生成器中:
$formOptions = array(
'class' => 'Acme\DemoBundle\Entity\User',
'multiple' => false,
'expanded' => false,
'property' => 'fullName',
'query_builder' => function(EntityRepository $er) use ($user) {
return $er->queryOwnedBy($user);
},
);
编辑
感谢ncatnow和unagi我更改了以前的函数以返回querybuilder
Thank's for ncatnow and unagi I've changed the previous functions to return the querybuilder
这篇关于Symfony形式query_buider和实体存储库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!