Using viaTable() in simple blog based on Yii2

I’m new to Yii. I’m trying to develop a simple blog using Yii2.

This is what I have in database:

post table:

id

title

content

author_id

published_date

category table:

id

title

I need to relate these two tables with hasMany.

I couldn’t manage to query posts by category. And also I wasn’t able to show which category the post relates to. How do I do all that?

If there’s any tutorial on creating a blog using Yii2, which specifically show the usage of viaTable() or other relation methods, it’d be more than helpful.

Thank you.

Since you’re mentioning viaTable, I assume post could belong to multiple categories and you have post_category junction table.

If that’s true then relation in Category would be:




/**

  * @return \yii\db\ActiveQuery

  */

public function getPosts()

{

    return $this->hasMany(Post::className(), ['id' => 'post_id'])->viaTable('{{%post_category}}', ['category_id' => 'id']);

}