2
我正在開發一些基於目錄的項目,其中包含無限嵌套(實際上,最高級別爲3,我猜,但必須是動態反正)。Yii 1.從類別及其子類別獲取產品[無限制嵌套]
讓我告訴就要做:
OrganizationCategory型號:
public function relations()
{
return array(
'organizations' => array(self::HAS_MANY, 'Organization', 'organization_category_id'),
'parent' => array(self::BELONGS_TO, 'OrganizationCategory', 'category_parent_id'),
'children' => array(self::HAS_MANY, 'OrganizationCategory', 'category_parent_id'),
);
}
public static function getParentCategories()
{
if (is_null(self::$categories))
{
self::$categories = array();
$criteria = new CDbCriteria();
$criteria->order = 't.category_title';
$criteria->condition = "t.category_parent_id IS NULL";
$arr = self::model()->with('children')->findAll($criteria);
foreach ($arr as $item)
self::$categories[$item->primaryKey] = $item;
}
return self::$categories;
}
public static function createTree($children, $counter)
{
$tree = '';
if(count($children)){
$tree .= CHtml::tag('ul', array('class'=>'menu_open_'.$counter));
foreach($children as $child):
$childrenSub = self::createTree($child->children, $counter+1);
$tree .= CHtml::tag('li', (empty($childrenSub) ? array('class'=>'no_child_li') : array()));
$organizations = Organization::model()->findByAttributes(array('organization_category_id'=>$child->category_id));
$tree .= CHtml::link($child->category_title, array('organizationCategory/view', 'slug'=>$child->category_slug));
$tree .= $childrenSub;
$tree .=CHtml::closeTag('li');
endforeach;
$tree .= CHtml::closeTag('ul');
}
return $tree;
}
CategoryController:
public function actionView($slug = '')
{
$model = $this->loadModelSlug($slug);
$organizationsList = Organization::getOrganizations($model->category_id);
$this->pageTitle=$model->category_title;
Yii::app()->clientScript->registerMetaTag($model->meta_description, 'description');
Yii::app()->clientScript->registerMetaTag($model->meta_keywords, 'keywords');
$this->render('view',array(
'model'=>$model,
'organizationsList'=>$organizationsList,
));
}
組織模型getOrganizations():
public static function getOrganizations($category_id) {
$criteria = new CDbCriteria;
$criteria->condition = 'organization_category_id = :cat_id';
$criteria->params = array(':cat_id'=>$category_id);
$result = self::model()->findAll($criteria);
return $result;
}
貓egory view.php
<?php if(!empty($model->children)) {
echo OrganizationCategory::model()->createTree($model->children, 1);
} ?>
<?php $i=1; foreach($model->organizations as $organization): ?>
blah blah blah
<?php $i++; endforeach; ?>
正如您可以猜到,現在,我只能得到這些產品,這是僅與當前顯示的類別相關聯。
我的目標是從類別及其所有子類別 - >子類別 - >子類別獲取產品。
我試圖找到解決方案几乎無處不在,但仍然無法在我的項目中實現這個瑣碎的任務。
我希望提供的任何幫助,感謝
您可以覆蓋CModel類,以通過覆蓋magic get方法調用時獲取父模型。 –
你好!我真的無法理解它如何幫助我從當前類別及其所有子類別 - >子類別 - >子類別獲取組織。 – Decd
你想要組織或產品嗎? –