duan205571 2014-05-14 13:46
浏览 49
已采纳

如何使用Doctrine 2按特定的一个到多个字段的值排序

I have an User, a Question and an Answer entity.

  • Each User has n Answers.
  • Each Answer has
    • an unique aid.
    • a question field holding the id of the Question answered.
    • the actual answer string given by the user, called answer.
  • Each Question has a unique qid.

I want to select all Users ordered by their answer to a specific question. That's how far I got:

$qid = 123; // The id of the question to order the users by.
$orderByDir = 'ASC';

$qb->select('u')
   ->from('EventManager_Entity_User', 'u')
   ->leftJoin('u.answers', 'a', \Doctrine\ORM\Query\Expr\Join::WITH, 'a.question = ' . $qid)
   ->orderBy('a.answer', $orderByDir);

$users = $qb->getQuery()->execute();

But the result isn't ordered :/

  • 写回答

2条回答 默认 最新

  • dqwh0108 2014-05-14 14:04
    关注

    I can't say for sure this is correct, but your query doesn't look quite right. Specifically the way you are joining Answers to Users. To me it looks like there is not foreign key relation between them in that join, even though there may be in your schema.

    Try this, it may be incorrect for your schema, but you should be able to understand what is going on. Assuming the join is the issue, the ordering should work.

    use Doctrine\Common\Collections\Criteria;
    
    $qb
        ->select('u')
        ->from('EventManager_Entity_User', 'u')
        ->join('u.answers', 'a')
        ->join('a.question', 'q')
    
        ->where('q.id = :question_id')
        ->setParameter('question_id', $qid)
    
        ->orderBy('a.answer', Criteria::ASC)
    ;
    

    I changed it to an inner join, without it some users not linked to answers not may be ordered like the rest.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 前端echarts坐标轴问题
  • ¥15 CMFCPropertyPage
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题
  • ¥15 谁会P4语言啊,我想请教一下
  • ¥15 这个怎么改成直流激励源给加热电阻提供5a电流呀
  • ¥50 求解vmware的网络模式问题 别拿AI回答
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳