简体   繁体   中英

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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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