Search code examples
phpidiorm

idiorm / paris has_many as_array result set


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?


Solution

  • 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.