Written by James McDonald

July 6, 2018

CakePHP with a query string /api/parts/getParts?sort=sort_order&direction=asc&limit=100

Returns items out of order. See below for the work-a-round

{
"parts": [
{
"sort_order": 10
},
{
"sort_order": 20
},
{
"sort_order": 30
},
{
"sort_order": 40
},
{
"sort_order": 60
},
{
"sort_order": 70
},
{
"sort_order": 120
},
{
"sort_order": 130
},
{
"sort_order": 140
},
{
"sort_order": 150
},
{
"sort_order": 160
},
{
"sort_order": 170
},
{
"sort_order": 200
},
{
"sort_order": 50
},
{
"sort_order": 62
},
{
"sort_order": 72
},
{
"sort_order": 80
},
{
"sort_order": 90
},
{
"sort_order": 110
}
]
}

I don’t get this because the sort_order database field is an int(11) and well an integer should sort numerically.

So this is the work-a-round but still no idea why it’s needed

// api/PartsController.php

public function getParts() {

        $parts = $this->Parts->find('all', [
            'fields' => ['sort_order'],
            'conditions' => [
                'active' => true,
                'NOT' => [
                    'co_visit' => true,
                ],
            ],
            'order' => [
                'sort_order + 0', // this is the magic the + 0 forces it to sort numerically
            ]
        ]
        );

        $this->set(compact('parts'));
        $this->set('_serialize', ['parts']);
    }

And the result

{
"parts": [
{
"sort_order": 10
},
{
"sort_order": 20
},
{
"sort_order": 30
},
{
"sort_order": 40
},
{
"sort_order": 50
},
{
"sort_order": 60
},
{
"sort_order": 62
},
{
"sort_order": 70
},
{
"sort_order": 72
},
{
"sort_order": 80
},
{
"sort_order": 90
},
{
"sort_order": 110
},
{
"sort_order": 120
},
{
"sort_order": 130
},
{
"sort_order": 140
},
{
"sort_order": 150
},
{
"sort_order": 160
},
{
"sort_order": 170
},
{
"sort_order": 200
}
]
}

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

The reCAPTCHA verification period has expired. Please reload the page.

You May Also Like…

Network speed test host to host

On Ubuntu / Debian apt-get install iperf3 On Windows download it from https://iperf.fr/iperf-download.php#windows Make...

Clear HSTS Settings in CHrome

Open chrome://net-internals/#hsts enter the domain in the query field and click Query to confirm it has HSTS settings...