Lanbo
Lanbo

Reputation: 15712

COUNT for table and Paginator in CakePHP

I have a model Catalog that is like this:

class Catalog extends AppModel {
  public $hasMany = array(
    'Entries' => array(
      'className' => 'Entry',
    );
  );
}

In my index view, I want to show the number of Entries per Catalog. I also want to make it possible for the user to sort the Catalogs by the number of Entries.

I'm a beginner with CakePHP, is there any way I can get the COUNT(entry_id) per Catalog and display it in the array? And to have it sorted via $this->Paginator?

Upvotes: 0

Views: 99

Answers (1)

aifarfa
aifarfa

Reputation: 3939

You can use virtual fields with custom query

in your Model

var $virtualFields = array(
    'entry_count' => 'SELECT COUNT(entry_id) FROM entries as Entry WHERE Entry.catalog_id = Catalog.id'
  );

Upvotes: 1

Related Questions