2

我无法使用 php idiorm/paris 获取 has_many 查询的结果。按照巴黎站点的示例,帖子的 has_many 结果作为对象返回。

太好了,我可以遍历对象并访问各个方法,但我想做的是将结果集作为关联数组传递给我的模板引擎进行显示。

例子:

   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
       }
   }

该 api 以这种方式工作:

   // 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();

我能够访问帖子对象并像这样打印结果集:

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

不过,我真正想做的是使用 as_array() 将整个结果集作为关联数组获取,受 as_array 用于单个行的方式中的某些字段的限制,例如

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

这个,或者像 $user->posts()->find_many()->as_array() 这样的调用不起作用。

使用 paris 访问此类结果集的正确方法是什么?

4

2 回答 2

2

将此方法添加到 idiorm.php 为我提供了所需的功能。

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;
}

现在我可以调用 $post_list = $posts()->find_array(); 或 $posts()->find_array('id','title'); 等等

于 2012-02-12T01:25:19.270 回答
1

find_one 返回一个模型对象,find_many 返回一个模型数组。如果要将整个结果集作为关联数组的数组,一种解决方案应该是使用 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);

或在 php 5.3+ 中(未测试)

$aa_posts = array_map(function($model) {return $model->as_array();} , $posts);
于 2012-03-26T14:45:27.767 回答