使用HABTM查找CakePHP中不显示引用表结果的查询


Find query not showing results from referenced table in CakePHP using HABTM

我在agent和Categories两个模型之间有一个HABTM关系。我遵循了这里的说明:http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html

我已经设置了表,创建了fk等。为了测试是否正在为agent上的查找查询检索类别,我放入了以下调试代码:

debug($this->AgentsCategories->find('all', array(
    'order' => array('Agent.name', 'Agent.address'), 
    'conditions' => array('Agent.id' => '59')
)));

结果数组:

array(
    (int) 0 => array(
        'Agent' => array(
            'id' => '59',
            'name' => 'MUTUAL UNDERWRITERS',
            'address' => 'Waipahu Branch
94-615 Kupuohi St #102
Waipahu, HI 96797',
            'telephone' => '808-688-2222',
            'fax' => '808-688-0769',
            'email' => null,
            'website' => 'http://www.mutualunderwriters.com',
            'island' => '1',
            'modified' => '2014-04-16 15:56:46'
        )
    )
)

只显示来自Agents表的信息,它不显示来自categories表的类别。id是FK。从指令中,我期望类似下面的例子:

Array
(
    [Recipe] => Array
        (
            [id] => 2745
            [name] => Chocolate Frosted Sugar Bombs
            [created] => 2007-05-01 10:31:01
            [user_id] => 2346
        )
    [Ingredient] => Array
        (
            [0] => Array
                (
                    [id] => 123
                    [name] => Chocolate
                )
           [1] => Array
                (
                    [id] => 124
                    [name] => Sugar
                )
           [2] => Array
                (
                    [id] => 125
                    [name] => Bombs
                )
        )
)

我做错了什么和/或我应该如何调试这个?谢谢你!

您的代理模型应该看起来像:

class Agent extends AppModel {
public $hasAndBelongsToMany = array(
    'Category' =>
        array(
            'className' => 'Category',
            'joinTable' => 'agents_categories', //or your table name
            'foreignKey' => 'agent_id',
            'associationForeignKey' => 'category_id',
            'unique' => true,
            'conditions' => '',
            'fields' => '',
            'order' => '',
            'limit' => '',
            'offset' => '',
            'finderQuery' => '',
            'with' => ''
        )
);
}

然后简单地进行如下搜索:

$this->Agent->find('all', array('order' => array('Agent.name', 'Agent.address'), 
                                'conditions' => array('Agent.id' => '59')));

您将得到预期的结果。