0

我正在用 CakePHP 建立一个站点。我有两个表,“类别”和“公司”,第三个将它们连接起来,称为“companies_categories”:

companies_categories
`id` int(10) NOT NULL AUTO_INCREMENT,
`company_id` int(10) NOT NULL,
`category_id` int(10) NOT NULL,

我想根据类别中的公司数量列出前 10 个类别,但我不知道该怎么做。

这是我的模型:

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,
            )
    );
}    
4

1 回答 1

0

您可以尝试以下方法:

$this->Category->find('list', array(
    'joins' => array(
        'table' => 'companies_categories',
        'alias' => 'CompaniesCategory',
        'type' => 'LEFT',
        'foreignKey' => false,
        'conditions' => 'Category.id = CompaniesCategory.category_id',
    ),
    'order' => 'COUNT(CompaniesCategory.id) DESC',
    'group' => 'Category.id',
    'limit' => 10,
));

您可能想查看 counterCache,然后它将company_count向您的表中添加一个字段,categories您可以这样做:

$this->Category->find('list', array('order' => 'company_count DESC', 'limit' => 10));
于 2012-07-26T22:42:42.810 回答