如何对findAll主义的方法进行排序? [英] How to sort findAll Doctrine's method?

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

问题描述

我一直在阅读Doctrine的文档,但无法找到对findAll()结果进行排序的方法。



我正在使用symfony2 +学说,这是我在控制器中使用的语句:



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



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



我一直试图通过这种方式将数组作为参数传递:



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



,但是它不起作用(也没有抱怨)。



是否可以在不构建DQL查询的情况下执行此操作?

解决方案

就像@Lighthart所示,是可以的,尽管它为控制器增加了很多脂肪并且不是干的。 / p>

您应该在实体存储库中真正定义自己的查询,这是简单且最佳的做法。

 使用Doctrine\ORM\EntityRepository; 

类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主义的方法进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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