我有一支团队'具有财产预算的实体'。我只想打印团队属性,我希望预算最多的团队出现在第一个位置,第二个,第三个......(DESC)。
但是使用此代码,它不起作用,我不明白为什么。
indexAction (控制器)
$em = $this->getDoctrine()->getManager();
$teams = $em->getRepository('FootballBundle:Team')->getAllTeamsSortedByDescBudget();
return $this->render('FootballBundle:Default:index.html.twig', array(
'teams' => $teams,
));
TeamRepository
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
*
* @ORM\Column(name="budget", type="integer")
*/
private $budget;
在这里,结果......
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 评论。
答案 0 :(得分:4)
将QueryBuilder
方法中的getAllTeamsSortedByDescBudget
查询更改为:
public function getAllTeamsSortedByDescBudget()
{
$qb = $this->createQueryBuilder('t')
->orderBy('t.budget', 'DESC');
return $qb->getQuery()->getResult();
}
答案 1 :(得分:0)
您还可以使用sort()执行排序。
public function getAllTeamsSortedByDescBudget() {
$qb = $this->createQueryBuilder('t')
->sort('t.budget', 'DESC');
return $qb->getQuery()->getResult();
}