## 在首頁模板中獲取指定分類下(含子欄目)的所有文章
View: 在網站經常要用到調用欄目下(含子欄目)的所有的文章,自己寫的方法,寫得不好勿怪
> \themes\hx\portal\index.html
<div class="gzcx_k_nr_r">
<ul class="clearfix">
<php>
$cid="";
$arr = json_decode(\app\portal\service\ApiService::allSubCategoriesCid(26),true);
foreach ( $arr as $key => $val) {
if( is_array($val) ) foreach( $val as $value) $cid.= $value.',';
}
if(!$cid){ $cid=26; }
</php>
<portal:articles limit="6" order="post.published_time DESC" categoryIds="$cid">
<li><a href="{:url('portal/Article/index',array('id'=>$vo.id,'cid'=>$vo.category_id))}"> <span class="gzcx_k_nr_r_img"><img src="{:cmf_get_image_url($vo.more.thumbnail)}"></span> <small>{$vo.post_title}</small></a></li>
</portal:articles>
</ul>
</div>
調用自定義API數據源獲取數據 allSubCategoriesCid(26)
> \app\portal\service\ApiService.php
/**
* [allSubCategoriesCid]根據path查詢,得到所有分類
* @param [string] $categoryId
* @return [子分類ID]
*/
public static function allSubCategoriesCid($categoryId)
{
$portalCategoryModel = new PortalCategoryModel();
$categoryId = intval($categoryId);
if ($categoryId !== 0) {
$category = $portalCategoryModel->field('path')->where('id', $categoryId)->find();
if (empty($category)) {
return [];
}
$categoryPath = $category['path'];
} else {
$categoryPath = 0;
}
$where = " status='1' AND delete_time='0' AND path like '$categoryPath-%'";
return $portalCategoryModel->where($where)->field('id')->select();
}
### 方法說明:
#### 根據指定的總分類id來查詢數據,方法里面是根據 path 的字段來查詢獲取子分類ID ,在頁面是通過json_decode將對象轉成數組,然后給標簽調用 categoryIds="$cid" ,方法寫得不太好,僅作參考(個人推薦使用AJAX實現相關的功能)