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

WHEN I try to do:

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

As a result, I get idas a string.

If I do this:

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

then it gives custom_idas an integer.

How can I get custom_idboth idwithout losing the data type. I read the documentation but did not find much help.

I think virtual fields can do. But is it possible inside a search query without using virtual fields, etc.

Thanks at Advance

+2
source share
2 answers

As of CakePHP 3.2

Query::selectTypeMap() , .

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

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

, . alias .

.

CakePHP 3.1

Query::typeMap(), , , , , .

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

.

, , , CakePHP, , __, , Articles id, Articles__id.

, Query::aliasField(), :

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

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

id string.

.

+5

, , , () type :

        $this->Users->schema()
            ->addColumn('is_licensed', [
                'type' => 'boolean',
            ])
            ->addColumn('total_of_licenses', [
                'type' => 'integer',
            ]);

        $fields = [
            'Users.id',
            'Users.username',
            'Users.first_name',
            'Users.last_name',
            'Users.active',
            'Users__is_licensed' => 'if(count(LicenseesUsers.id)>=1,true,false)',
            'Users__total_of_licenses' => 'count(LicenseesUsers.id)',
            'Users.created',
            'Users.modified',
            'Languages.id',
            'Languages.name',
            'Countries.id',
            'Countries.name',
            'UserRoles.id',
            'UserRoles.name',
        ];

     $where = [
        'contain' => ['UserRoles', 'Countries', 'Languages'],
        'fields' => $fields,
        'join' => [
            'LicenseesUsers' => [
                'table' => 'licensees_users',
                'type' => 'LEFT',
                'conditions' => [
                    'Users.id = LicenseesUsers.users_id'
                ],
            ],
        ],
        'group' => 'Users.id'
    ];

    // Set pagination
    $this->paginate = $where;

   // Get data in array
   $users = $this->paginate($this->Users)->toArray();
0

Source: https://habr.com/ru/post/1656056/


All Articles