Cakephp 3.0:将选定的字段转换为int

时间:2016-06-21 08:42:14

标签: cakephp cakephp-3.0

我有一个包含字段的表

int id|text title|text content|int articleCommentCount|

当我访问json url /articles.json时,我得到类似

的内容
{
 "announcements": [
   {
    "id": 2,
    "title":"title",
    "articleCommentCount": 16 //Notice value is an int
    }
 ]
}

现在由于我的api的结构,我想将articleCommentCount标记为comment_count(仅适用于json输出)。所以我修改了控制器中的find()并指定了类似的东西

->select([
'comment_count'=>'articleCommentCount'])

正如您所看到的,articleCommentCount的值被镜像到comment_count,如下所示

{
 "announcements": [
   {
    "id": 2,
    "title":"title",
    "articleCommentCount": 16
   "comment_count": "16" //Notice value was mirrored BUT is a JSON STRING
    }
 ]
}

问题: 如何避免出现字符串而不是 int

的问题

CakePHP版本3.2

1 个答案:

答案 0 :(得分:2)

使用typeMap()方法

->select(['comment_count'=>'articleCommentCount'])
->typeMap(['comment_count' => 'integer'])