custom query in entity field type

二次信任 提交于 2019-11-28 10:07:37
Sergi

The easiest way is to add a group by in the query:

$form = $this->createFormBuilder()
  ->add('users', 'entity', array(
    'class' => 'UserBundle:Users',
    'query_builder' => function(EntityRepository $er) {
      return $er->createQueryBuilder('u')
                ->groupBy('u.id')
                ->orderBy('u.name', 'ASC');
      },)
    )
->getForm();

I don't think you can use straight DQL here; you're using the QueryBuilder object so you have to use the QueryBuilder API to build your query.

More info here:

http://www.doctrine-project.org/docs/orm/2.0/en/reference/query-builder.html

Edit

Alternatively you could group by name?

return $er->createQueryBuilder('u')
    ->groupBy('u.name')
    ->orderBy('u.name');

Edit

Okay... If you absolutely need to use DQL there is another way. You create a custom repository for your entity, and in that define a method with your custom query. Symfony's documentation covers this process here:

http://symfony.com/doc/2.0/book/doctrine.html#custom-repository-classes

Let's assume you create a method called findDistinctUsers. It's then simply a case of changing the code in your form to:

return $er->findDistinctUsers();

I haven't checked this but it should work. Hope this helps :)

Don't use in Repository method:

->getQuery()
->getResult();

just alone:

->createQueryBuilder('u')
->groupBy('u.name')
->orderBy('u.name');

like in 'query_builder' => function (EntityRepository $er) {

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!