MartinZeltin
5 months ago

How to sort by a related table's column?

Posted 5 months ago by MartinZeltin

I have two tables (users and statuses) that are related and I would like to sort them alphabetically by the user's status. I can't just sort them by users.status column because then it won't be in alphabetical order.

How could I achieve this if I'm able to get users with statuses like this?

    $users = User::with('status')->get();

    // This doesn't seem to be working
    $users = User::with('status')->orderBy('status.descriptoin', 'asc')->get();

Users table

+----+------------+--------+
| id |  username  | status |
+----+------------+--------+
|  1 | john123    |      5 |
|  2 | billy_joe  |      1 |
|  3 | martin_lee |      5 |
|  4 | two_cents  |      2 |
|  5 | Lucy       |      3 |
|  6 | Bill2      |      4 |
+----+------------+--------+

Statuses table

+----+-------------+
| id | description |
+----+-------------+
|  1 | VIP         |
|  2 | Junior      |
|  3 | Senior      |
|  4 | Banned      |
|  5 | New member  |
+----+-------------+

Desired result (users sorted alphabetically by status)

+---------+------------+------------+
| user_id |  username  |   status   |
+---------+------------+------------+
|       6 | Bill2      | Banned     |
|       4 | two_cents  | Junior     |
|       1 | john123    | New member |
|       3 | martin_lee | New member |
|       5 | Lucy       | Senior     |
|       2 | billy_joe  | VIP        |
+---------+------------+------------+

Please sign in or create an account to participate in this conversation.