2

I have a table with fields

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

When I access the json url /articles.json I get something like

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

Now because of the structure of my api, I want articleCommentCount to be labelled comment_count (For json output sake only). So I modified my find() in the controller and specified something like;

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

As you can see the value of articleCommentCount is mirrored to comment_count like below

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

Question: How do I avoid this issue of getting a String instead of an int

CakePHP Version 3.2

Lukesoft
  • 953
  • 1
  • 12
  • 31

1 Answers1

3

Use the typeMap() method

->select(['comment_count'=>'articleCommentCount'])
->typeMap(['comment_count' => 'integer'])
Dakota
  • 458
  • 2
  • 9
  • 1
    It should be noted that this would override the complete typemap, causing the other fields to lose their type mappings. Also the type map is used in other places too, not only for casting selected fields, which is why one may want to use `selectTypeMap()` instead. – ndm Jun 21 '16 at 11:59