-1

假设这个模式:

  • 类别(ID,名称)
  • 文章(id、categoryId、writerId、标题、内容)
  • 作家(身份证、姓名、年龄、地点)

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

类别型号:

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。

4

2 回答 2

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);
            }
        }
    }
}
于 2015-12-01T10:29:40.640 回答
0

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

$writers = Category::find()->where(['id' => $id])->one()->getWriters()->all();
$articles = [];
foreach ($writers as $writer) {
  $articles[] = $writer->getArticles()->all();
}
于 2015-12-01T16:22:22.437 回答