2

I'm using Laravel Query Builder to get a set of rows, ordering them by 2 columns, ticket_id then id (previously created_at). However the result orders them by ticket_id (correct), but the id (or created_at) secondary order is incorrect. Am I approaching this wrong, misunderstanding ordering?

Here's my query:

$responses = Response::where('status', '=', 'closed');
                       ->select('id', 'ticket_id', 'created_at', 'author_id')
                       ->orderBy('ticket_id', 'id')
                       ->get();

Which in turn, returns:

  0 => array:3 [
    "ticket_id" => 14
    "id" => 71
    "time" => "2018-05-25 08:55:03"
  ]
  1 => array:3 [
    "ticket_id" => 14
    "id" => 75
    "time" => "2018-05-25 12:48:45"
  ]
  2 => array:3 [
    "ticket_id" => 14
    "id" => 72
    "time" => "2018-05-25 08:55:53"
  ]
  3 => array:3 [
    "ticket_id" => 13
    "id" => 70
    "time" => "2018-05-25 08:53:50"
  ]
  4 => array:3 [
    "ticket_id" => 13
    "id" => 76
    "time" => "2018-05-29 12:30:46"
  ]
  5 => array:3 [
    "ticket_id" => 13
    "id" => 74
    "time" => "2018-05-25 11:30:36"
  ]

You see for ticket 14, the order is 71, 75, 72, rather than 71, 72, 75.

Here's the table structure too:

+------------+------------------+------+-----+---------+----------------+
| Field      | Type             | Null | Key | Default | Extra          |
+------------+------------------+------+-----+---------+----------------+
| id         | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| ticket_id  | int(11)          | NO   |     | NULL    |                |
| author_id  | int(11)          | NO   |     | NULL    |                |
| status     | int(11)          | NO   |     | 0       |                |
| content    | text             | NO   |     | NULL    |                |
| created_at | timestamp        | YES  |     | NULL    |                |
| updated_at | timestamp        | YES  |     | NULL    |                |
| assets     | text             | YES  |     | NULL    |                |
+------------+------------------+------+-----+---------+----------------+
Jam3sn
  • 1,077
  • 4
  • 17
  • 35

1 Answers1

5

orderBy() recives the column name as first parameter and the orientation ASC, DESC as the second.

orderBy('ticket_id', 'id') should be orderBy('ticket_id', 'desc')->orderBy('id','desc')

  • I'm such an idiot for missing that in the docs. Thanks, been banging my head against the desk for too long with this one. – Jam3sn Jun 11 '18 at 15:32