1

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?

Álvaro González
  • 142,137
  • 41
  • 261
  • 360

1 Answers1

3

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.

tarikul05
  • 1,843
  • 1
  • 16
  • 24
  • That's it, thank you very much. I admit I don't fully understand the mechanism, though. If the field needs to be already defined, what's the point of the ad-hoc definition? It's just a way to override the original definition? – Álvaro González Mar 24 '17 at 10:20