【发布时间】:2016-08-08 18:32:26
【问题描述】:
我是 yii2 的新手。我已经阅读了有关 sof 的文档和一些答案,但我仍然无法处理 yii2 中的关系。我能够为该问题创建原始 mysql 查询,但我不知道如何使用 yii2 关系创建相同的查询。我对 via、joinWith 和一些关键概念感到困惑。我将尽可能描述问题。 我有四个模型。
Category, CategoryNews, NewsTags, Tags
category table - cat_id, cat_name
news_category table - nc_id, nc_cat_id, nc_news_id
news_tags table - nt_id, nt_news_id, nt_tag_id
tags table - tag_id, tag_name
我需要的是每个类别的标签模型对象,即对于每个类别,我需要属于该类别的所有新闻标签。请求来自gridview。 生成的关系是:
Category Model:
public function getNewsCategory()
{
return $this->hasMany(NewsCategory::className(), ['nc_cat_id' => 'cat_id']);
}
NewsCategory Model:
public function getNcNews()
{
return $this->hasOne(News::className(), ['news_id' => 'nc_news_id']);
}
public function getNcCat()
{
return $this->hasOne(Category::className(), ['cat_id' => 'nc_cat_id']);
}
NewsTags Model:
public function getNtNews()
{
return $this->hasOne(News::className(), ['news_id' => 'nt_news_id']);
}
public function getNtTag()
{
return $this->hasOne(Tags::className(), ['tag_id' => 'nt_tag_id']);
}
News Model:
public function getNewsCategory()
{
return $this->hasMany(NewsCategory::className(), ['nc_news_id' => 'news_id']);
}
public function getNewsTags()
{
return $this->hasMany(NewsTags::className(), ['nt_news_id' => 'news_id']);
}
Tags Model:
public function getNewsTags()
{
return $this->hasMany(NewsTags::className(), ['nt_tag_id' => 'tag_id']);
}
即。每个类别包含多个新闻,每个新闻包含多个标签,我需要与每个类别相关的所有标签。 更准确地说,在 gridview 上,我需要所有类别和一个显示与这些类别相关的所有标签的列。 请帮忙!!
【问题讨论】: