CakePHP 连接模型及其自身的关系

CakePHP join model and its own relationships

Shop 模型中我有:

public $belongsTo = array(
    'Company' => array()
);

模型 Company 在其模型 class 中定义了自己的关系。如何在执行时获取 Company relation

$this->Shop->find('all',
       array(
           'conditions' => array(
               'Shop.loyaltycard' => 0,
            )
       )
);

如果您已正确声明关系,find() 将自动获取第一级关联模型,前提是您没有更改默认的递归级别(即 1)。

如果失败,请尝试以下操作:

$this->Shop->recursive=1;
$this->Shop->find('all',array(
    'conditions' => array(
        'Shop.loyaltycard' => 0,
    )
));

有关模型属性的更多信息 recursive

另一种选择是加载 Containable 行为,这将允许您过滤希望获取的关系。

$this->Shop->Behaviors->load('Containable'); //or make your model act as Containable 
$this->Shop->contain('Company');
$this->Shop->find('all',array(
    'conditions' => array(
        'Shop.loyaltycard' => 0,
    )
));

更多关于 ContainableBehavior

另外,请将您的关系声明修改为以下内容:

public $belongsTo = array(
    'Company'
);

不确定空数组如何影响你们的关系,但它可能会导致失败。请注意,这仅在您遵循 CakePHP conventions.

后才有效

如果您不想查找所有相关型号而只想查找公司,您可以添加 $actsAs = array('Containable'); 在您的商店模型中,然后像这样进行搜索:

$this->Shop->find('all',array(
    'conditions' => array(
        'Shop.loyaltycard' => 0,
    ),'contain' => array(
         'Company'
));

查看cakephp可包含http://book.cakephp.org/2.0/en/core-libraries/behaviors/containable.html