【问题标题】:Find query not showing results from referenced table in CakePHP using HABTM使用 HABTM 查找未显示 CakePHP 中引用表的结果的查询
【发布时间】:2014-08-05 16:52:18
【问题描述】:

我在代理和类别这两个模型之间有一个 HABTM 关系。我已按照此处的说明进行操作: http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html

我已经设置了表格,创建了 FK 等。为了测试是否正在检索类别以在代理上进行查找查询,我输入了以下调试代码:

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 表中的信息,不显示agents.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
                )
        )
)

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

【问题讨论】:

  • 显示您的代理模型代码

标签: php mysql sql cakephp has-and-belongs-to-many


【解决方案1】:

您的代理模型应如下所示:

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

你会得到预期的结果。

【讨论】:

  • 答案中应该出现的两个词recursive 和containable =)。
  • 感谢您的帮助,我的代理模型看起来像这样,查询也像这样,但输出与未显示类别数组的示例不匹配。
  • 嗨@AD7six,你的评论是什么意思?
  • @dev808 recursive 用于广泛控制 find 调用返回的内容。 containable 提供了更精细的控制 - 它们是“答案”,没有它们,答案是不完整的。
猜你喜欢
  • 1970-01-01
  • 2014-02-02
  • 2011-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-22
  • 1970-01-01
相关资源
最近更新 更多