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

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

问题描述

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

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

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

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).

有没有什么方法可以在不构建 DQL 查询的情况下做到这一点?

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

推荐答案

正如@Lighthart 所示,是的,这是可能的,尽管它为控制器增加了大量的脂肪并且不是 DRY.

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 DoctrineORMEntityRepository;

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:

/**
 * @ORMTable(name="User")
 * @ORMEntity(repositoryClass="AcmeUserBundleEntityRepositoryUserRepository")
 */
class User
{
    ...
}

最后,在您的控制器中:

Finally, in your controller:

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

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

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