如何排序findAll Doctrine的方法 [英] How to sort findAll Doctrine's method

查看:82
本文介绍了如何排序findAll Doctrine的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读Doctrine的文档,但是我没有找到一种排序findAll()结果的方法。



我使用symfony2 + doctrine,这是我在我的Controller中使用的语句:



$ this-> getDoctrine() - > getRepository('MyBundle:MyTable') - > findAll();



,但是我希望结果按升序的用户名排序。



我一直在尝试以这种方式传递一个数组作为参数:



findAll(array('username'=>'ASC'));



但它不工作(它也不会抱怨)。



没有构建DQL查询有什么办法吗?

解决方案

作为@Lighthart,如图所示,是的,尽管它向控制器添加了显着的胖子,但并不是DRY。 / p>

您应该在实体存储库中定义自己的查询,这是简单和最佳实践。

 使用Doctrine\ORM\EntityRepository; 

class UserRepository扩展EntityRepository
{
public function findAll()
{
return $ this-> findBy(array(),array('用户名'=>'ASC'));
}
}

然后你必须告诉你的实体寻找查询存储库:

  / ** 
* @ ORM\Table(name =User)
* @ ORM\Entity(repositoryClass =Acme\UserBundle\Entity\Repository\UserRepository)
* /
类用户
{
...
}

最后,在您的控制器中:

  $ this-> getDoctrine() - > getRepository('AcmeBundle:User') - > findAll(); 


I've been reading Doctrine's documentation, but I haven't been able to find a way to sort findAll() Results.

I'm using symfony2 + doctrine, this is the statement that I'm using inside my Controller:

$this->getDoctrine()->getRepository('MyBundle:MyTable')->findAll();

but I want the results to be ordered by ascending usernames.

I've been trying to pass an array as an argument this way:

findAll( array('username' => 'ASC') );

but it doesn't work (it doesn't complain either).

Is there any way to do this without building a DQL query?

解决方案

As @Lighthart as shown, yes it's possible, although it adds significant fat to the controller and isn't DRY.

You should really define your own query in the entity repository, it's simple and best practice.

use Doctrine\ORM\EntityRepository;

class UserRepository extends EntityRepository
{
    public function findAll()
    {
        return $this->findBy(array(), array('username' => 'ASC'));
    }
}

Then you must tell your entity to look for queries in the repository:

/**
 * @ORM\Table(name="User")
 * @ORM\Entity(repositoryClass="Acme\UserBundle\Entity\Repository\UserRepository")
 */
class User
{
    ...
}

Finally, in your controller:

$this->getDoctrine()->getRepository('AcmeBundle:User')->findAll();

这篇关于如何排序findAll Doctrine的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆