Attribute whose value should be used as index of the query result array

28 views
Skip to first unread message

Necip

unread,
Nov 2, 2018, 5:55:08 AM11/2/18
to Fat-Free Framework
I am working since 2 years with the yii-Framework. There's a comfortable feature: The index of the result set can be determined in Yii using the attribute "Index". 

"index": the name of the AR attribute whose value should be used as index of the query result array.

e.g.
$criteria = new DBCriteria;
$criteria->Index = 'id';
...
$model = TestModel::model()->findAll($criteria)


Example:

We have a table 'obj' with following records:
ID Name
10 Test1
13 Test2
15 Test3

F3 delivers the result starting with the index 0 incrementaly.

$f3->set('result', $db->exec('
SELECT ID, Name FROM obj');

$f3->get('result')[0]; // is the record with the id 10
$f3->get('result')[1];   // is the record with the id 13
$f3->get('result')[2];   // is the record with the id 15


but I would prefere to have this result:


$f3->get('result')[10]; // is the record with the id 10
$f3->get('result')[13];   // is the record with the id 13
$f3->get('result')[15];   // is the record with the id 15


Is there a way to do the same with F3?

ikkez

unread,
Nov 2, 2018, 7:33:36 AM11/2/18
to f3-fra...@googlegroups.com
hi. well your request assumes that there is a primary key on the table, and that this key is exactly on only one field (no compond key). Both is mostly true, but not a restiction on the F3 SQL mapper.
But yes there's a way to do this in PHP of course.. loop through all results and reorder them by key. In case you use cortex, you can do this with $results = $mapper->find()->getBy('id);
Otherwise create a helper function like this one

function orderById($results) {
    $out
= array();
   
foreach ($results as $model)
        $val
= $model->get('id');
       
if (!empty($val))
            $out
[$val] = $model;
   
return $out;
}


Reply all
Reply to author
Forward
0 new messages