假设这个模式:
- 类别(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。