4

I'm using Cakephp 3.2.7 as a framework and create a query with select alias.

 $posts = $this->Posts->find()
 ->select(['id' => 'Posts.id','userid'=>"Posts.user_id"])->toArray();

I want to get id as string not integer (the column type in mysql is integer) and get the userid as integer (the column type in mysql is also integer) but use alias convert it to string.

Is there any way to fetch all of Id columns in all of model as string or at least can define data type in query?

Faezeh
  • 83
  • 1
  • 6
  • Why do you need to change the type? PHP is a loosely typed language so it doesn't make a massive difference whether you have an integer or a string. Converting the `id` to a string in your code whilst maintaining the column as an integer in the database is likely to lead to issues with saving! – drmonkeyninja Sep 28 '16 at 08:27
  • if you use `id` or `*_id` words as alias and field type is integere then cakephp auto converts it into integer values. try with use `author_id` instead of `userid` then check. and let me know its working or not – Haresh Vidja Sep 28 '16 at 09:39
  • 2
    **http://stackoverflow.com/questions/35650306/cakephp-3-x-how-to-change-the-data-type-of-a-selected-alias** – ndm Sep 28 '16 at 12:30
  • @drmonkeyninja I want to use it in the response of API for mobile and change it to string to prevent issues in data type definition in different OS. – Faezeh Sep 28 '16 at 20:44

2 Answers2

0

Actually I agree with @drmonkeyninja and I don't know why you want to do this.

Also I don't guarantee that what I'm about to write is safe and is a clean way to achieve what you are trying to do.

Anyway you can modify the table schema and change the column type. See the manual

$this->Posts->schema()->addColumn('userid', [
    'type' => 'integer',
])
->addColumn('id', [
    'type' => 'string',
]);
arilia
  • 9,373
  • 2
  • 20
  • 44
  • thanks for your response. I haven't ever used schema and I am not sure weather it change anything in database or just it convert column type after data fetch from database? – Faezeh Oct 01 '16 at 07:15
0

Finally I found the solution. I add a mutator to entity of post class.

protected function _getId()
{
    return (string)$this->_properties['id'];

}

that force id to return as string.

Faezeh
  • 83
  • 1
  • 6