为了账号安全,请及时绑定邮箱和手机立即绑定

YII框架怎样在一个页面同时显示出父分类和子分类的名字?

YII框架怎样在一个页面同时显示出父分类和子分类的名字?

Yii
跃然一笑 2018-09-13 15:11:14
这是数据库的表结构这是想在前台显示的这是我的控制器里的方法function actionCatshow(){$category_model = Category::model();$cnt = $category_model -> count();$per = 10;$page = new Pagination($cnt,$per);$sql = "select b.cat_name, b.cat_id, b.parent_id, a.cat_name as parent_name from {{category}} a INNER JOIN {{category}} b ON a.cat_id = a.parent_id order by cat_id $page->limit;";$category_infos = $category_model -> findAllBySql($sql);$page_list = $page->fpage(); $this -> renderPartial('catshow',array('category_infos'=>$category_infos,'page_list'=>$page_list));} 
查看完整描述

1 回答

?
江户川乱折腾

TA贡献1851条经验 获得超5个赞

这个好办啊,你利用关联数据库很容易实现啊。
举个例子:
你上面的parent_id存放父类的表的id,为{{分类}}建立数据模型,然后在模型中添加与父类的关系。
public function relations()
{
return array(
// 和parent建立“属于(多对一)”关系,下面的参数第二个是Parent数据表,第三个是外 // 键关联的字段

'parent'=>array(self::BELONGS_TO,'Parent','parent_id'),
);
}
这时候,你不需要联合查询,直接$results=Category::model()->findAll();
此时你想显示父类的名字,只需要
foreach($results as $result)
{
//显示序号<td>

//显示名字<td>
echo $result->cat_name;
//显示父类名字<td>
echo $result->parent->name; //此处就是用的Yii模型中提供的关联数据库的方式,
}



查看完整回答
反对 回复 2018-10-22
  • 1 回答
  • 0 关注
  • 845 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信