Laravel:OrderBy不工作?

时间:2017-08-02 11:06:10

标签: php laravel

我试图通过Roleplay(升序)获取模态payslips_collected ASC顺序的所有记录。

升序意味着从最低值开始并上升。我没有得到......这是我制作的桌子的结果。

+----+------------------+--------+-------------+-----------------+-----------------+--------------+-----------+
| ID |    Username      | Shifts |  Completed  |  Registered     | Website Login   | Client Login | Last Seen |
+----+------------------+--------+-------------+-----------------+-----------------+--------------+-----------+
| 1  |  Danny Fure      |   29   | 1 year ago  |  43 minutes ago | 43 minutes ago  | 1 second ago |           |
| 2  |  James Mack      |   0    | 1 year ago  |  1 second ago   | 2 days ago      | 1 second ago |           |
| 3  |  Peter Barlow    |   0    | 1 year ago  |  1 second ago   | 2 days ago      | 1 second ago |           |
| 4  |  Adam Chapman    |   0    | 1 year ago  |  1 second ago   | 2 days ago      | 1 second ago |           |
| 5  |  Danny Burrows   |   0    | 1 year ago  |  1 second ago   | 2 days ago      | 1 second ago |           |
| 6  |  Kieran Root     |   0    | 1 year ago  |  1 second ago   | 2 days ago      | 1 second ago |           |
| 8  |  Ashton David    |   0    | 1 year ago  |  1 second ago   | 2 days ago      | 1 second ago |           |
| 9  |  Someone Special |   0    | 1 year ago  |  1 second ago   | 2 days ago      | 1 second ago |           |
| 10 |  Kelly Clark     |   0    | 1 year ago  |  1 second ago   | 2 days ago      | 1 second ago |           |
| 11 |  Abbie Grove     |   0    | 1 year ago  |  1 second ago   | 2 days ago      | 1 second ago |           |
+----+------------------+--------+-------------+-----------------+-----------------+--------------+-----------+
抱歉,我有点搞砸了,它没有正确格式化。但无论如何,主要问题是它以DESC顺序显示,(降序)显示最低之前的最高值。

有谁能告诉我为什么要这样做?

原始查询:

select * from `users` where exists (select * from `srp_user_statistics` where `users`.`id` = `srp_user_statistics`.`user_id` order by `payslips_collected` asc)

代码:

$players = Player::whereHas('roleplay', function ($query) use($orderType) {
    $query->orderBy('payslips_collected', $orderType);
});

4 个答案:

答案 0 :(得分:1)

我认为您正在使用排序子查询而不是主要选择查询,所以请尝试在外面编写订单子查询
 喜欢这个

$players = Player::whereHas('roleplay', function ($query) use($orderType) {
    $query->orderBy('payslips_collected', $orderType);
})->orderBy('id', $orderType);

修改: -

select `users`.* from `users` join `srp_user_statistics` on `users`.`id` = `srp_user_statistics`.`user_id`
order by `srp_user_statistics.payslips_collected` asc

答案 1 :(得分:0)

试试这个

$players = Player::has('roleplay')
    ->orderBy('payslips_collected', $orderType)
    // ...

答案 2 :(得分:0)

您可以对结果集合进行排序:

$sorted_players = $players->sortByDesc('payslips_collected');

或者简单地反转您的实际结果

$sorted_players = $players->reverse();

答案 3 :(得分:0)

在某些情况下(我不知道什么时候),Laravel会将自己的默认排序顺序放在你自己面前...这显然会导致问题。

解决此问题的一个技巧是在添加自己的行之前使用此行重置查询中的所有先前订单:

$query->getQuery()->orders = null;