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