這是數據庫的表結構這是想在前臺顯示的這是我的控制器里的方法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模型中提供的關聯數據庫的方式,
}
- 1 回答
- 0 關注
- 915 瀏覽
添加回答
舉報
0/150
提交
取消