Dail
Dail

Reputation: 4608

How to count the result using find() in CakePHP 2.2.4?

I am using Cakephp 2.2.4 and I need to retrive a list of Lead that belongs to the user (id = 106).

The result of the query is:

array(
    (int) 0 => array(
        'Lead' => array(
            'id' => '6',
            'user_id' => '106',
            'date' => '2012-12-31 22:15:23',
            'ip' => '127.0.0.1',
            'service_id' => '1',
            'location' => 'Rome',
            'message' => 'Message Message',
            'telephone' => null,
            'active' => null
        ),
        'User' => array(
            'id' => '106',
            'email' => '[email protected]',
            'pwd' => '0433c024cb08be13000d59a347e640482843f46f177e95749dc6599c259617fd3491dcb940b47693cbbc7f65a2cc5ef62deca2e600c1be133ad54170f7d1fbd1',
            'role_id' => '3',
            'active' => '1'
        ),
        'Service' => array(
            'id' => '1',
            'name' => 'Primo servizio'
        ),
        'Estimate' => array(
            (int) 0 => array(
                'id' => '1',
                'lead_id' => '6',
                'user_id' => '106'
            )
        )
    )
)

It looks good but I need to count the Estimates (Estimate array), I would like to retrive the number of the estimates, and not the array with all the fields (of estimates table).

How can i do it?

I need :

Lead array as it shown

User array as it shown

Service array as it shown

Estimate (only the total number of the estimates... in this case 1)

The find is very simple:

$options = array('conditions' => array('User.id' => 106));

debug($this->Lead->find('all', $options));

Upvotes: 0

Views: 1158

Answers (2)

Mark Grey
Mark Grey

Reputation: 10257

Without diving too far into the internals of the Cake ORM, assuming you don't need to do this immediately at query time, couldn't you just get the count of the estimate array programmatically after the fetch?

http://php.net/manual/en/function.count.php

$leads = $this->Lead->find('all',$options);
foreach($leads as $lead){
  //get the number of estimates for every lead result
  $lead_num = count($lead['Estimate']);
}

Alternatively, you could manually write a join query for this one fetch and execute it using the Cake Model class's query method. Without knowing the specifics of your table schema and model relations its hard to give specifics about how to structure the query, but this shouldn't be too difficult by just look at your table spec and extracting a sql COUNT statement for every Estimate with given id.

Upvotes: 0

cowls
cowls

Reputation: 24354

Try something like this, not 100% sure it'll work but worth a go if not I'd advise trawling the cakephp docs for retrieving your data:

$options = array(
    'fields' => array('Lead.*', 'User.*', 'Service.*', 'count(Estimate.id)'),
    'conditions' => array('User.id' => 106)
);

Upvotes: 3

Related Questions