0

私は CakePHP でサイトを構築しています。「categories」と「companys」の 2 つのテーブルと、それらを結合する「companies_categories」という 3 つ目のテーブルがあります。

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

company_countテーブルにフィールドを追加する counterCache を調べると、次のcategoriesように実行できます。

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