好的,我现在在我的电脑上:)。
在 ShopModel 中:
class ShopModel extends AppModel {
public $hasMany = array(
'Catalog' => array(
// binding params here...
),
);
}
在目录模型中:
class CatalogModel extends AppModel {
public $hasMany = array(
'Product' => array(
// binding params...
),
),
}
...然后继续...
如果你不想在所有动作中获取过多的数据,你应该在AppModel中设置:
class AppModel extends Model {
public $recursive = -1;
}
在您调用具有关联的查找函数的控制器操作中:
$this->Shop->Behaviors->load('Containable');
$big_array = $this->Shop->find('all', array(
'conditions' => array(
//...
),
'contain' => array(
'Catalog' => array(
'Product' => array(
// etc, you get the point :)
),
),
),
));
还可以声明 $belongsTo 关联,这样您就可以从任何地方访问任何内容,如下所示:
$this->Catalog->Behaviors->load('Containable');
$big_array = $this->Catalog->find('all', array(
'conditions' => array(
//...
),
'contain' => array(
'Product' => array(
// ...
),
'Shop' => array(
// ...
),
),
));
编辑
我看到你有一个 Product->Category 关系,我猜它是用 $belongsTo 定义的。如果您进行上述查询,您将获得大量重复查询(许多产品中的相同类别)。您可以使用$this->Category->find('list'),但我经常发现这不合适,因为它只返回一个字段(如果有人知道如何使用列表类型获取更多字段,我将不胜感激)。为此,我的解决方法是在 Category 模型中创建一个自定义函数,如下所示:
class Category extends AppModel {
public function getSorted ($options = array()) {
$temp= $this->find('all', $options);
$output = array();
foreach ($temp[$this->alias] as $row) {
$output[$this->alias][$row['id']] = $row;
}
unset($temp);
return $output;
}
}
然后在控制器中我会声明两个数组,一个没有类别关联的大数组和一个类别列表:
$this->loadModel('Category');
$this->set('categories', $this->Category->getSorted());
这样,我可以在视图中的任何需要的位置按类别 ID 获取所需的类别行。