Feature Request #1259

ORM_Iterator as_array() with referenced primary key

Added by towfx - almost 3 years ago. Updated over 2 years ago.

Status:Closed Start date:
Priority:Low Due date:
Assignee:John Heathco % Done:

0%

Category:Libraries:ORM
Target version:2.4
Resolution:fixed Points:

Description

I would like to quickly access result by primary key.

Eg result output to be "similar" as below:

$users = ORM::factory('user_model')->find_all()->as_array();

//returned as
$users = array(
  '123' => ORM::Factory(user_model, 123), 
  '456' => ORM::Factory(user_model, 456), 
  '789' => ORM::Factory(user_model, 789)
)

notice that the array index is the table primary key

eg usage: get username for id 456
$usersr456->username;

eg usage: get status for id 456
$usersr456->email;

instead or next() or prev() or rewind() why not jump exactly to the designated object where possible. This could be a cool feature to add. In any way I don't see any performance trade off instead of conviniences.

This feature also could be similar to temporary table with primary key in the array.

Simple solution:

38        public function as_array($index_by=null)
39        {
 ...
46    
47                foreach ($results as $obj)
48                {
                    if($index_by != null)
49                       $array[$obj->$index_by] = new $class($obj);
                    else
                       $array[] = new $class($obj);
50                }
51            }
52    
53            return $array;
54        }

Parameter $index_by can be any field. Just in case want to use 'username' field as reference key


... ->as_array('username');
//now can use
$users['towfx']->email; 
// to get email if already got username

History

Updated by John Heathco almost 3 years ago

Nifty idea for a feature, but it should default to returning whatever order is given by the iterator (otherwise the orderby feature would be meaningless). If an argument is passed, that will be used as the index, but it must be passed explicitly (including a primary_id).

Updated by John Heathco over 2 years ago

  • Tracker changed from Bug Report to Feature Request
  • 11 set to 2.3.4

Updated by John Heathco over 2 years ago

  • Resolution set to fixed

Updated by John Heathco over 2 years ago

  • Status changed from New to Closed

Also available in: Atom PDF