Order articles by number of matched tags in CakePHP 3 -
i've searched high , low answer, think common problem.
in cakephp 3 app have:
- articles
- tags
and working habtm relationship between two.
edited:
what need, way order these results number of tags shared articles.
this close i've gotten. needless doesn't work:
protected function _getrelatedarticles(){ //collect ids of tags related current article $tag_ids = array_map(function($value){ return $value->id; }, $this->tags); $articles = tableregistry::get('articles'); $tags = tableregistry::get('tags'); //subquery find tags associated both original article , related //count create priority can sorted $subquery = $tags->find()->matching('articles', function($q)use($tag_ids){ return $q->where([ 'and' => [ 'articles.id' => 'articleid', //i suspect wrong. not sure how reference article id main query 'tags.id in' => $tag_ids ] ]); })->count('*'); //main query $query = $articles->find() ->select([ 'id', 'name', 'priority' => $subquery]) //incorporate sub-query ->order(['priority' => 'desc']) //sort results priority, should @ point count of shared tags ->contain('tags') ->distinct(['articles.id']) ->where(['articles.id !=' => $this->id]); //make main query find articles share tags current. works if(!empty($tag_ids)){ $query->matching('tags', function ($q) use($tag_ids){ return $q->where(['tags.id in' => $tag_ids]); }); } return $query->toarray(); }
what have here based on this, unanswered, question.
Comments
Post a Comment