Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
295 views
in Technique[技术] by (71.8m points)

php - Cakephp-3.x: How to change the data type of a selected alias?

WHen i try to do :

$fields = array('id' => 'custom_id', 'title' => 'some_name');

The result I get has id as a string.

If I do:

$fields = array('custom_id', 'title' => 'some_name');

then it gives custom_id as integer.

How can I obtain custom_id as id without loosing the data type. I read the documentation but didn't found much help.

There is something that virtual fields can do I think. But is it possible inside the find query without the use of virtual fields etc?

Thanks in Advance

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As of CakePHP 3.2

you can use Query::selectTypeMap() to add further types, which are only going to be used for casting the selected fields when data is being retrieved.

$query = $table
    ->find()
    ->select(['alias' => 'actual_field', /* ... */]);

$query
    ->selectTypeMap()
    ->addDefaults([
        'alias' => 'integer'
    ]);

You can use any of the built-in data types, as well as custom ones. In this case the alias field will now be casted as an integer.

See also

With CakePHP 3.1 and earlier

you'll have to use Query::typeMap(), which will not only affect the selected field when data is being retrieved, but in various other places too where data needs to be casted according to the field types, which might cause unwanted collisions, so use this with care.

$query
    ->typeMap()
    ->addDefaults([
        'alias' => 'integer'
    ]);

See also

Change the type of existing columns

Changing the type of an existing column of a table is possible too, however they need to be set using a specific syntax, ie in the column alias format used by CakePHP, that is, the table alias and the column name seprated by __, eg, for a table with the Articles alias and a column named id, it would be Articles__id.

This can be either set manually, or better yet retrieved via Query::aliasField(), like:

// $field will look like ['Alias__id' => 'Alias.id']
$field = $query->aliasField('id', $table->alias());

$query
    ->selectTypeMap()
    ->addDefaults([
        key($field) => 'string'
    ]);

This would change the the default type of the id column to string.

See also


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...