2

I'm having trouble getting the results of a has_many query using php idiorm/paris. Following the example from the paris site the has_many result for posts returns as an object.

That's great, and I can run through the object and access individual methods, but what I want to be able to do is pass the result set as an associative array off to my template engine for display.

Example:

   class Post extends Model {
   }

   class User extends Model {
       public function posts() {
           return $this->has_many('Post'); // Note we use the model name literally - not a    pluralised version
       }
   }

The api works this way:

   // Select a particular user from the database
   $user = Model::factory('User')->find_one($user_id);

   // Find the posts associated with the user
   $posts = $user->posts()->find_many();

I am able to access the posts object and print the result set like this:

   // echo each post id
   foreach ($posts as $post) {
      echo $post->id;
   }

What I'd really like to be to do though, is use as_array() to get the entire resultset as an associative array, limited by certain fields in the way as_array works for an individual row, e.g.

   $post_list = $posts()->as_array(id,title,post,date);

This, or a call on something like $user->posts()->find_many()->as_array() don't work.

What is the correct way to access this type of result set using paris?

Unused
  • 41
  • 1
  • 4

2 Answers2

2

Adding this method to idiorm.php gives me the desired functionality.

public function find_array() {
    if (func_num_args() === 0) {
        return $this->_run();
    }
    $args = func_get_args();
    $array = array();
    foreach ($this->_run() as $r) {
        $array[] = array_intersect_key($r, array_flip($args));
    }
    return $array;
}

Now I can call $post_list = $posts()->find_array(); or $posts()->find_array('id','title'); etc.

Unused
  • 41
  • 1
  • 4
  • 1
    This is something you should really do in a class that extends `ORM` rather than directly in the `ORM` otherwise you won't be able to upgrade easily. Have you thought about opening this as a pull request on Idiorm? – Treffynnon Jan 15 '13 at 15:44
  • 1
    This feature was added to Idiom/Paris. [Docs](http://idiorm.readthedocs.org/en/latest/querying.html?highlight=find_array#as-an-associative-array) – alttag Aug 18 '14 at 14:06
1

find_one returns a Model object, find_many returns an array of Models. If you want to get the entire result set as an array of associative array, one solution should be to use array_map

function model_as_array($model) {
    return $model->as_array();
}

$posts = $user->posts()->find_many();
$my_view->posts = array_map(model_as_array, $posts);
var_dump($my_view->posts);

or in php 5.3+ (not tested)

$aa_posts = array_map(function($model) {return $model->as_array();} , $posts);
benkaemu
  • 11
  • 1