## 根據欄目ID獲取相關的文章
做企業站時候,前臺點擊欄目后,查詢出相關文章,在框架中是用標簽來讀取的,不是很靈活。我這里寫了個方法,方便前臺使用AJAX來調用數據!
/**
* 根據欄目id獲取文章
* @return [json] [相關文章]
*/
public function getwzbycid()
{
$cid = $this->request->param('cid');
if (empty($cid)) {
$this->error('欄目不存在!');
}else{
//1,獲取下級欄目
$arr = json_decode(\app\portal\service\ApiService::allSubCategoriesCid($cid),true);
$erjiid='';
foreach ( $arr as $key => $val) {
if( is_array($val) ) foreach( $val as $value) $erjiid .= $value.',';
}
//2,查詢欄目所有推薦的新聞
$field = 'a.*,b.id AS post_category_id,b.list_order,b.category_id';
$join = [
['__PORTAL_CATEGORY_POST__ b', 'a.id = b.post_id']
];
$portalPostModel = new PortalPostModel();
$articles = $portalPostModel->alias('a')->field($field)->join($join)
->where(function($query) use ($erjiid) {
$category = $erjiid;
if (!empty($category)) {
$query->where('b.category_id','in',$category);
}
})
->where('a.is_top','1') //置頂推薦的
->order('update_time', 'DESC')
->select();
return json(['data'=> $articles ]);
}
}
where有三種寫法:表達式法,數組法,然后閉包法;這里使用了第三種閉包的寫法!
閉包寫法:where里面,是一個匿名函數。函數很熟悉,匿名函數不過是少了個函數名稱。
如果條件里面需要傳遞參數,加上 **use (變量)**