CakePHP 3.0 : Cast selected fields to int

标签 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 输出)。所以我修改了 Controller 中的 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
    }
 ]
}

问题: 如何避免获取 String 而不是 int

的问题

CakePHP 版本 3.2

最佳答案

使用typeMap()方法

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

关于CakePHP 3.0 : Cast selected fields to int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37939514/

相关文章:

php - Cakephp,排序关联表

php - 调试 LAMP/CakePHP 站点内存泄漏?

javascript/jquery 更新多个选择框选项

cakephp - patchEntity 似乎删除了外键

sql - 如何比较两个日期的月份部分?

php - Join 语句中的 Cake PHP3 子查询

database - Cakephp 发现没有按预期工作

php - 如何在CakePHP中更改时间戳的格式?

mysql - cakephp3.0 分页给出连接表错误

php - 如何在cakephp 3请求中获取浏览器名称?