linkyndy
linkyndy

Reputation: 17900

CakePHP: include fieldname alias under related model

I am willing to group MySQL results by a column, and also count the records which belong to the same category:

$this->find('all', array(
    'fields' => array('UserCheckin.id', 'UserCheckin.capital_id', 'COUNT(UserCheckin.id) as capital_checkins'), 
    'group' => 'UserCheckin.capital_id'
));

The problem is that capital_checkins is grouped as a separate key in the returned array, whilst I would like it to be under the UserCheckin model. Here's how the results are returned:

Array
(
[0] => Array
    (
        [UserCheckin] => Array
            (
                [id] => 3
                [capital_id] => 10
            )

        [0] => Array
            (
                [capital_checkins] => 2
            )

        [Capital] => Array
            (
                [id] => 10
                [name] => London
            )

    )

[1] => Array
    (
       ...
    )

)

Is there a way to include the alias under UserCheckin model?

Upvotes: 2

Views: 3440

Answers (2)

Laguna Web Design
Laguna Web Design

Reputation: 332

'COUNT(UserCheckin.id) as UserCheckin__capital_checkins'

http://book.cakephp.org/2.0/en/models/virtual-fields.html#virtual-fields-in-sql-queries

Upvotes: 0

lxa
lxa

Reputation: 3332

In cakephp 1.3 you can use virtual field:

in your UserCheckin model:

var $virtualFields = array(
    'capital_checkins' => 'COUNT(UserCheckin.id)'
);

IMPORTANT UPDATE: As @Rob Wilkerson correctly notices, adding a virtual field with aggregate function permanently to your model will [probably] mess up your find queries which do not have a GROUP BY (implicitly group all rows in MySQL or just fail with SQL error in SQL Server). Solution is to add a virtual field temporarily at a runtime before query that uses it:

$this->virtualFields['capital_checkins'] = 'COUNT(UserCheckin.id)';

$result = $this->find('all', array(
    'fields' => array('UserCheckin.id', 'UserCheckin.capital_id', 'UserCheckin.capital_checkins'), 
    'group' => 'UserCheckin.capital_id'
));

//reset virtual field so it won't mess up subsequent finds
unset($this->virtualFields['capital_checkins']);

return $result;

Upvotes: 3

Related Questions