我有这些模特:
class Article extends \yii\db\ActiveRecord
{
.....
public function getTags()
{
return $this->hasMany(Tag::className(), ['id' => 'tag_id'])->viaTable('rel_tag_article', ['article_id' => 'id']);
}
}
class News extends \yii\db\ActiveRecord
{
.....
public function getTags()
{
return $this->hasMany(Tag::className(), ['id' => 'tag_id'])->viaTable('rel_tag_news', ['news_id' => 'id']);
}
}
class Tag extends \yii\db\ActiveRecord
{
.....
public function getRelTagArticles()
{
return $this->hasMany(RelTagArticle::className(), ['tag_id' => 'id']);
}
public function getRelTagNews()
{
return $this->hasMany(RelTagNews::className(), ['tag_id' => 'id']);
}
}
在控制器中
class ArticleController extends \yii\web\Controller
{
public function actionArticle($id_article)
{
$article = User::find($id_article);
...... here ....
return $this->render('article');
}
}
在...here...
下,我必须找到与我的实际文章有共同标签的新闻。什么是正确的方法?
答案 0 :(得分:0)
##您可以使用文章活动记录来获取标签,然后使用标签来获取新闻##
class ArticleController extends \yii\web\Controller
{
public function actionArticle($id_article)
{
$article = User::find($id_article);
$tags=$article->tags;
$related_news=array();
foreach($tags as $tag) {
$related_news=array_merge($tag->getRelTagNews(),$related_news);
}
return $this->render('related_news');
}
}