如何做一个点击标签 显示使用标签的文章
求一个具体点的思路
求一个具体点的思路
2017-03-16
<?php namespace frontend\widgets\post; /** * 文章列表组件 */ use common\models\PostModel; use common\models\RelationPostTagsModel; use common\models\TagsModel; use frontend\models\TagForm; use frontend\models\PostForm; use Yii; use yii\base\Widget; use yii\data\Pagination; use yii\db\Query; use yii\helpers\Url; class PostWidget extends Widget { /** * 文章列表的标题 * @var string */ public $title = ''; /** * 显示条数 * @var int */ public $limit = 3; /** * 是否显示更多 * @var bool */ public $more = true; /** * 是否显示分页 * @var bool */ public $page = true; public function run() { $tag = Yii::$app->request->get('tag'); $curPage = Yii::$app->request->get('post',1); //查询条件 if(!empty($tag)){ $ids = []; //方法一:使用with关联表 //$tags = new TagForm(); //$ids = $tags->getIdsByTag(['tag_name'=>$tag]); //方法二:先查询标签id,再查询文章id数组 //$data = TagsModel::find()->where(['tag_name'=>$tag])->asArray()->one(); //$ids = RelationPostTagsModel::getPostIds($data['id']); //方法三:使用join关联表 $data = (new Query()) ->select('a.post_id') ->from(['a'=>RelationPostTagsModel::tableName()]) ->join('LEFT JOIN',['b'=>TagsModel::tableName()],'a.tag_id=b.id') ->where(['b.tag_name'=>$tag]) ->orderBy(['a.post_id'=>SORT_DESC]) ->all(); if(!empty($data)){ foreach ($data as $value){ $ids[] = $value['post_id']; } } //print_r($ids);exit; $cond = ['id'=>$ids,'is_valid'=>PostModel::IS_VALID]; }else{ $cond = ['=','is_valid',PostModel::IS_VALID]; } $res = PostForm::getList($cond,$curPage,$this->limit); $result['title'] = $this->title?:'最新文章';//组件标题支持自定义 $result['more'] = Url::to(['post/index']); $result['body']= $res['data']?:[]; //是否显示分页 if($this->page) { $pages = new Pagination(['totalCount'=>$res['count'],'pageSize'=>$res['pageSize']]); $result['page'] = $pages; } return $this->render('index',['data'=>$result]); } }
//文章列表组建里面 $curPage = \Yii::$app->request->get('page', 1); $tagName = \Yii::$app->request->get('tag'); $cond = []; if ($tagName) { $tags = new Tags(); $tag = $tags ->find() ->with('postid') ->where(['tag_name'=>$tagName]) ->asArray() ->one(); if (isset($tag['postid']) && !empty($tag['postid'])) { foreach ($tag['postid'] as $v) { $id[] = $v['post_id']; } $cond = ['id' => $id, 'is_valid' => Posts::IS_VALID]; } }
// tagModel数据模型类 public function getPostid() { return $this->hasMany(RelationPostTags::className(), ['tag_id'=>'id']); }
在组件里添加条件。
$tags = Yii::$app->request->get('tag');
if($tags) {
$tag = new PtModel();
$post_id = $tag->getPostid($tags);
if ($post_id) {
foreach ($post_id as $v) {
$id[] = $v['post_id'];
}
$cond = ['id' => $id,'is_valid'=>PostsModel::IS_VALID];
}
}
$res = PostsModel::getList($cond,$curPage,$this->limit);
/*关联表*/
public function getPostid($id){
$res = PtModel::find()->select('post_id')->where('tag_id ='.$id)->asArray()->all();
return $res;
}
举报