## 在首页模板中获取指定分类下(含子栏目)的所有文章
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实现相关的功能)