如何从数据库中更新数组值,然后将其传递给CakePHP中的视图


How do I update an array value from the database before passing it to the view in CakePHP?

我基本上希望能够在将结果发送到我的视图之前通过函数传递值…

public function listing() {
    $this->set('posts',  $this->paginate('Post'));
}

所以我想在这里写些东西,例如:

    foreach($posts as $post){
        $post["Post"]["timestamp"] = $this->timeago($post["Post"]["timestamp"]);
    }

然后我想用这个字段对结果进行分页,并将'posts'设置为我发送给视图的整体数组-使用'timeago'函数更新了时间戳。最好的方法是什么?

您可以考虑在find()之后在模型行为中实现这些方法。
更多信息请参见:http://book.cakephp.org/2.0/en/models/callback-methods.html

这是基本的php。为了修改数组,您需要使用$key,如下所示:

foreach ($posts as $key => $post) {
    $posts[$key]["Post"]["timestamp"] = $this->timeago($post["Post"]["timestamp"]);
}

但是你真正想要的是在实际输出之前修改时间戳:

// in your view ctp
foreach ($posts as $post) {
    ...
    $formattedTimestamp = $this->Time->timeAgoInWords($post["Post"]["timestamp"]);
    echo '<span>' . $formattedTimestamp . '</span>';
    ...
}

在我看来,输出格式不应该在模型层中完成——尤其是不应该使用回调。如果您碰巧没有使用格式化的字段,那么您的模型就会在记录上循环,而没有任何意义。

另一种可能性:使用引用。

// Note the "&"
foreach($posts as &$post){
    $post["Post"]["timestamp"] = $this->timeago($post["Post"]["timestamp"]);
}

这实际上会在访问每个$post时修改$posts数组。