vitto
vitto

Reputation: 19496

Count number of posts in cakephp

I'm trying to create a menu in cake php where I can also know how many articles are inside the section, should I use a manual query, or does exist some existing method to do it?

My site menu:
- Works (12)
- Photos (35)
- Stuff (7)
- Contacts

My problem is also I didn't get how I can access to data like this for every view, this should be a main menu, so I should use this in every view but If i put it in default.ctp, every model deosn't exist, because I cannot access it from a view.

Does exist some page which talks about this?

Upvotes: 0

Views: 1463

Answers (2)

JohnP
JohnP

Reputation: 50029

Since those are separate models that are not related to each other, you'll need to do a manual count.

$this->Model->find('count');

EDIT

Ok, so looks like you are talking about different models.

If this is used in a menu, that means it will be shown in all pages.

You have two ways of doing this.

You can do it by having an AppController for you application. Basically, you can put this code in the beforeRender method so it runs everytime your a request is rendered

function beforeRender() {
   App::import('Model', array('Work', 'Photo', 'Stuff'));
   $work = new Work();
   $workCount = $work->find('count');

   //do the same for the other

   $this->set('workCount', $workCount);
}

Have a look at this for more details on callbacks : http://book.cakephp.org/view/977/Controller-Methods#Callbacks-984

Secondly, you can do this via a helper. You can put the same code (that is inside the bforeRender) into a helper, and you can call the helper method.

You can look here for more info on creating a helper : http://book.cakephp.org/view/1097/Creating-Helpers

Upvotes: 1

Andrew Ashbacher
Andrew Ashbacher

Reputation: 989

The CounterCache behavior will help you out: http://book.cakephp.org/view/1033/counterCache-Cache-your-count

Upvotes: 0

Related Questions