仅在yii2中获取相关记录

时间:2015-12-01 10:24:05

标签: yii2 yii2-advanced-app yii2-model

假设这个架构:

  • 类别(id,名称)
  • 文章(id,categoryId,writerId,title,content)
  • 作家(身份证,姓名,年龄,地点)

如果我从类别级别开始,我希望能够获得特定作者撰写的所有文章。那是类别>作家>文章,文章应该只属于该类别。

类别模型:

class Category extends ActiveRecord
{
    ...
    public function getArticles()
    {
        return $this->hasMany(Article::className(), ['categoryId' => 'id']);
    }

    public function getWriters()
    {
        return $this->hasMany(Writer::className(), ['id' => 'writerId'])->via('articles');
    }
}

作家模型:

class Writer extends ActiveRecord
{
    ...
    public function getArticles()
    {
        return $this->hasMany(Article::className(), ['writerId' => 'id']);
    }

    public function getCategories()
    {
        return $this->hasMany(Category::className(), ['id' => 'categoryId'])->via('articles');
    }
}

文章模型:

class Article extends ActiveRecord
{
    ...
    public function getCategory()
    {
        return $this->hasOne(Category::className(), ['id' => 'categoryId']);
    }

    public function getWriter()
    {
        return $this->hasOne(Writer::className(), ['id' => 'writerId']);
    }
}

如果我执行以下操作:

$category = Category::find()->with(['writers'])->where(['id' => 1])->one();
var_dump($category->writers[0]->articles);

无论类别如何,都会返回writers[0]的所有文章。如何让它仅返回category.id = 1。

2 个答案:

答案 0 :(得分:1)

试试这个

$category = Category::find()->where(['id' => 1])->one();
if ($category !== null) {
    $articles = $category->articles;
    if ($articles !== null) {
        foreach ($articles as $article) {
            if ($article->writer !== null) {
                var_dump($article->writer);
            }
        }
    }
}

答案 1 :(得分:0)

我无法测试它,但它看起来可能类似于:

$writers = Category::find()->where(['id' => $id])->one()->getWriters()->all();
$articles = [];
foreach ($writers as $writer) {
  $articles[] = $writer->getArticles()->all();
}