I’m building a site in CakePHP. I have two tables, “categories” and “companies” and a third one that joins them called “companies_categories”:
companies_categories
`id` int(10) NOT NULL AUTO_INCREMENT,
`company_id` int(10) NOT NULL,
`category_id` int(10) NOT NULL,
I want to list the top 10 categories based on the number of companies in the category, but I’m not sure how to go about it.
Here’s my models:
class Company extends AppModel {
public $name = 'Company';
var $hasAndBelongsToMany = array(
'Category' =>
array(
'className' => 'Category',
'joinTable' => 'companies_categories',
'foreignKey' => 'company_id',
'associationForeignKey' => 'category_id',
'unique' => true,
)
);
}
class Category extends AppModel {
public $name = 'Category';
public $useTable = 'categories';
// Set up the relationships
var $hasAndBelongsToMany = array(
'Company' =>
array(
'className' => 'Company',
'joinTable' => 'companies_categories',
'foreignKey' => 'category_id',
'associationForeignKey' => 'company_id',
'unique' => true,
)
);
}
You could try the following:
You may want to look into counterCache, which will then add a
company_countfield to yourcategoriestable and you could just do: