简体   繁体   English

Yii 2搜索2对多对多关系

[英]Yii 2 search in 2 many to many relation

I have these models : 我有这些模型:

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']);
    }
}

And in the controller 并在控制器中

class ArticleController extends \yii\web\Controller
{
    public function actionArticle($id_article)
    {


    $article = User::find($id_article);

    ...... here ....


    return $this->render('article');
    }

}

Under ...here... I have to find the news that have common tags with my actual article. ...here...我必须找到与我的实际文章有共同标签的新闻。 What is the right way? 什么是正确的方法?

## You can use article active record to get tags and in turn use tags to get news ## ##您可以使用文章活动记录来获取标签,然后使用标签来获取新闻##

   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');
      }        
    }

Visit this yii2 page 访问此yii2页面

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM