Symfony/Doctrine - createQueryBuilder orderBy

2022-01-03 00:00:00 php symfony doctrine-orm repository

我有一个带有属性预算"的团队"实体.我只想打印团队属性,我希望预算最大的团队出现在第一、第二、第三......(DESC).

I have a 'Team' Entity with a property 'budget'. I just want to print the teams properties and i want that the team with the biggest budget appear in first position, the second, the third... (DESC).

但是使用此代码,它不起作用,我不明白为什么.

But with this code, it does not work and i don't understand why.

indexAction(控制器)

    $em = $this->getDoctrine()->getManager();
    $teams = $em->getRepository('FootballBundle:Team')->getAllTeamsSortedByDescBudget();


    return $this->render('FootballBundle:Default:index.html.twig', array(
        'teams' => $teams,
    ));

团队存储库

public function getAllTeamsSortedByDescBudget()
{
    $q = $this->createQueryBuilder('a');
    $q->select()->from('FootballBundle:Team', 't')->orderBy('t.budget', 'DESC');

    return $q->getQuery()->getResult();
}

树枝视图

<h1>Teams list</h1>
<ul>
    {% for team in teams  %}
        <li>{{ team.name }} - {{ team.championship }} - {{ team.budget|number_format(2, '.', ',') }}£</li>
    {% endfor  %}
    <br/>
</ul>

Team.php 实体

/**
 * @var integer
 *
 * @ORMColumn(name="budget", type="integer")
 */
private $budget;

这里,结果......

And here, the result ...

Teams list

Manchester City FC - Premier League - 100,000,000.00£
Arsenal FC - Premier League - 50,000,000.00£
Leicester City - Premier League - 20,000,000.00£
Crystal Palace FC - Premier League - 5,000,000.00£
Chelsea FC - Premier League - 100,000,000.00£

切尔西...哈哈

编辑:更正!请参阅takeit 评论.

EDIT : CORRECTED ! See the takeit comment.

推荐答案

getAllTeamsSortedByDescBudget 方法中的 QueryBuilder 查询更改为:

Change your QueryBuilder query in getAllTeamsSortedByDescBudget method to:

public function getAllTeamsSortedByDescBudget() 
{ 
    $qb = $this->createQueryBuilder('t')
        ->orderBy('t.budget', 'DESC');

    return $qb->getQuery()->getResult(); 
}

相关文章