Search code examples
cakephpcakephp-2.9

TableAlias__ColumnAlias syntax in virtual fields not being parsed as documented


Docs state that we can name calculated fields using a syntax like Timelog__TotalHours and PHP will parse it as:

[0] => Array
(
    [ProductsItems] => Array
        (
            [Total] => 50
    )
)

In my CakePHP/2.9.4 set up I'm trying it in several places, such as pagination, but I get the column name handled as any other string:

[0] => Array
(
    [ProductsItems__Total] => 50
)

My test code in the controller is:

$this->Paginator = $this->Components->load(
    'Paginator',
    array(
        'fields' => array(
            "CONCAT_WS(' ', Usuario.nombre, Usuario.apellidos) AS Usuario__Empleado",
        ),
        'contain' => array(
            'Usuario',
        ),
        'limit' => 2,
    )
);
debug($this->Paginator->paginate());

... and prints:

array(
    (int) 0 => array(
        (int) 0 => array(
            'Usuario__Empleado' => 'Juan García'
        ),
        'Usuario' => array(
            'id' => '56'
        )
    ),
    (int) 1 => array(
        (int) 0 => array(
            'Usuario__Empleado' => 'María López'
        ),
        'Usuario' => array(
            'id' => '385'
        )
    )
)

Do I need explicitly to enable this feature somewhere?


Solution

  • First you should define the virtual field before your query (can be model or controller).

    $this->CurrentModel->Usuario->virtualFields['Empleado'] = 0;
    $this->Paginator = $this->Components->load(
        'Paginator',
        array(
            'fields' => array(
                "CONCAT_WS(' ', Usuario.nombre, Usuario.apellidos) AS Usuario__Empleado",
            ),
            'contain' => array(
                'Usuario',
            ),
            'limit' => 2,
        )
    );
    debug($this->Paginator->paginate());
    

    It should work.