Cakephp查找递归关联



我的Cakephp应用程序具有以下关系船模型

class Category extends AppModel {
public $hasAndBelongsToMany = array(
'Product' => array(
'className' => 'Product',
'joinTable' => 'products_categories',
'foreignKey' => 'category_id',
        'associationForeignKey' => 'product_id',
        'unique' => 'keepExisting',
    ),
);
}
class Product extends AppModel {
public $primaryKey = 'id';
public $hasMany = array(
    'ProductSwatch' => array(
        'className' => 'ProductSwatch',
        'foreignKey' => 'product_id',
         'dependent' => true
    ),
    'ProductDimension' => array(
        'className' => 'ProductDimension',
        'foreignKey' => 'product_id',
         'dependent' => true
    ),
    'ProductCare' => array(
        'className' => 'ProductCare',
        'foreignKey' => 'product_id',
         'dependent' => true
    ),
    'ProductDimension' => array(
        'className' => 'ProductDimension',
        'foreignKey' => 'product_id',
        'dependent' => false,
    ),
    'ProductCare' => array(
        'className' => 'ProductCare',
        'foreignKey' => 'product_id',
        'dependent' => false,
    ),
    'Review' => array(
        'className' => 'Review',
        'foreignKey' => 'product_id',
         'dependent' => true,
    )
);
}

当我找到所有的Category元素时,只有产品模型的内容会出现,当我们获取Categories模型时,有没有办法获得产品关联(ProductDimension、ProductSwatches等)?

默认情况下,CakePHP 2递归级别仅为一级关联。可以使用findrecursive选项(或模型属性)来获取深度关联。

有关模型recursive特性的详细信息,请参见:http://book.cakephp.org/2.0/en/models/model-attributes.html#recursive

例如:

$this->Category->find('all', array(
    'recursive' => 2,
    'conditions' => array(), // Your conditions, etc.
));

另一个(也是更好的方法)是使用Containable行为。

添加

public$actsAs=数组('Container');

以启用Containable行为。然后你可以使用:

$this->Category->find('all', array(
    'contain' => array(
        'Product' => array(
            'ProductSwatch',
            'ProductDimension',
            'ProductCare',
            'Review',
        ),
    ),
    'conditions' => array(), // Your conditions, etc.
));

以获取更深层次的关联。

有关Containable行为和更深层次关联的更多信息,请参阅http://book.cakephp.org/2.0/en/core-libraries/behaviors/containable.html#containing-更深层次的关联

最新更新