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…

Squarespace Image Export

To gain continued access to your Squarespace website images after cancelling your subscription you have several...

MySQL 8.x GRANT ALL STATEMENT

-- CREATE CREATE USER 'tgnrestoreuser'@'localhost' IDENTIFIED BY 'AppleSauceLoveBird2024'; GRANT ALL PRIVILEGES ON...

Exetel Opt-Out of CGNAT

If your port forwards and inbound and/or outbound site-to-site VPN's have failed when switching to Exetel due to their...