Php Yii-在dropdownlist中显示具有两个以上级别的treeview
我有一个具有这种结构的数据库表Php Yii-在dropdownlist中显示具有两个以上级别的treeview,php,database,yii,relationship,Php,Database,Yii,Relationship,我有一个具有这种结构的数据库表 id title parent_id is_parent parent_id是父元素的id,我将is_parent添加为布尔值以显示作为父元素的元素 我想从这个数据库中提取一个树状视图,并在下拉列表中显示它。以下是我想要的: level1 level2 child1 child2 level2_2 child1 child2 level1_2 ... 目前,如果在我的模型中只有两个级别(父级和子级
id title parent_id is_parent
parent_id是父元素的id,我将is_parent添加为布尔值以显示作为父元素的元素
我想从这个数据库中提取一个树状视图,并在下拉列表中显示它。以下是我想要的:
level1
level2
child1
child2
level2_2
child1
child2
level1_2
...
目前,如果在我的模型中只有两个级别(父级和子级),我可以这样做:
public function relations()
{
return array(
'getparent' => array(self::BELONGS_TO, 'Region', 'parent_id'),
'childs' => array(self::HAS_MANY, 'Region', 'parent_id', 'order' => 'title ASC'),
);
}
并且认为:
<?php echo $form->dropDownListRow($model,'region',CHtml::listData(Region::model()->findAll('is_parent=0'),'id', 'title','getparent.title'),array('prompt'=>'Choose')); ?>
我不知道如何更改模型中的关系或更改listData结构以获得我想要的结果。Optgroup(在下拉列表中)不能嵌套,因此必须放弃组。
只需创建自己的$model::getList()函数
我认为你不应该使用“是父母”,“父母id”就足够了。getList()如下所示:
public static function getList($id=0) {
$list = array();
$models = Region::model()->findAllByAttributes(array('parent_id'=>$id));
foreach ($models as $model) {
$childList = Region::getList($model->id);
array_merge($list, array($model->id => $model->title, $childList);
}
return $list;
}
当您调用它时,它是递归的,而不使用params-您从parent\u id=0
开始,然后获取所有树
如果您需要缩进,请在此函数中使用其他参数来设置它(并在每个级别增加它)我像这样使用它
,它返回一个空的下拉列表,我在这里出错了吗?@MahsaTeimourikia,使用Region::getList()
。getList是Region类的静态函数。在Yii API上找不到dropDownListRow
func,可能只是dropDownList?2.尝试调试我的func-addvar_dump(Region::getList())代码>在视图中…或var_dump($models,…)
内部函数。啊,那是因为我使用的是Yii引导,我也尝试了使用CHtml::dropDownList,没有结果,我将尝试调试,看看问题出在哪里,然后我将共享结果
public static function getList($parent_id=null,$dash='',$list=array()) {
$parents = ObjectCategory::find()->where(['parent_id' => $parent_id])->all();
foreach($parents as $id => $p) {
$list[$p->id] = $dash.$p->name;
$list = ObjectCategory::getList($p->id,"-".$dash,$list);
}
return $list;
}
// call on view
echo $form->field($model, 'parent_id')->dropDownList(backend\models\ObjectCategory::getList(null,''),['prompt' => 'Parent Category']);