artisticre's avatar

Querying DB

I am not sure how to query the database based on what I want. If I had a table in my blade view I want to query the database by id as follows

9 10 11 12
5 6 7 8
1 2 3 4

But it is querying like

12 11 10 9
8 7 6 5
1 2 3 4 
```
```
        $completed = CompletedWeekend::orderBy('id', 'desc')->get();

```
0 likes
5 replies
tykus's avatar

Are the values constrained to 1-12, or was that simply by way of example? Similarly, are you always grouping together 4 values?

There are different solutions available to you depending on the data you might be working with.

artisticre's avatar

Those are the id's as entered in the table. Does that make sense?

tykus's avatar

It doesn't really answer the question...

Anyway, as a general solution (for any range IDs) you can use a common table expression (CTE) query as follows:

WITH groupings AS (    
  SELECT
    id, 
    NTILE(3) OVER (ORDER BY id) as group_number
  FROM your_table_name
)
SELECT id
FROM groupings
ORDER BY group_number DESC, id ASC

NTILE takes a value for the number of groups you wanted to create, these will be numbered 1 - n which can then be used for sorting.

Staudenmeir's Laravel-CTE package is available to integrate into your Eloquent model(s) if you prefer to avoid writing a raw SQL query in your application.

Tray2's avatar

It looks like you are doing a snake sort,

Those are kind of tricky, you need to have another field that decides the order of the ids.

JussiMannisto's avatar

What's the use case? It might make more sense to do some of this in code rather than SQL.

Please or to participate in this conversation.