Hello. I need to get data from model using junction table.
I have Video, Category and VideoCategory (junction model of Video and Category) models.
My Video model is like this
<?php
namespace common\models;
use common\models\query\VideoQuery;
use Yii;
use yii\behaviors\BlameableBehavior;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\helpers\FileHelper;
/**
* This is the model class for table "video".
*
* @property string $video_id
* @property string $title
* @property string|null $about
* @property int|null $created_by
* @property int|null $created_at
* @property int|null $updated_at
*/
class Video extends ActiveRecord {
public $categories;
// ---some code---
//--then i save the video categories using aftersave() method.
public function afterSave($insert, $changedAttributes) {
parent::afterSave($insert, $changedAttributes);
$this->deleteExistingCategories();
if (isset($_POST['Video']['categories'])) {
$this->saveVideoCategories($_POST['Video']['categories']);
}
}
public function deleteExistingCategories() {
VideoCategory::deleteAll(['video_id' => $this->video_id]);
}
public function saveVideoCategories($categoriesList) {
foreach ($categoriesList as $category) {
$videoCategory = new VideoCategory();
$videoCategory->video_id = $this->video_id;
$videoCategory->category_id = $category;
$videoCategory->save();
}
}
}
My category model is
<?php
namespace common\models;
use Yii;
/**
* This is the model class for table "category".
*
* @property int $id
* @property string $category_name
* @property int|null $created_by
* @property int|null $created_at
* @property int|null $updated_at
*/
class Category extends \yii\db\ActiveRecord {
//just gii generated simple code.
}
My VideoCategory model is
<?php
namespace common\models;
use Yii;
/**
* This is the model class for table "video_category".
*
* @property int $id
* @property string $video_id
* @property int $category_id
* @property int|null $created_by
* @property int|null $created_at
* @property int|null $updated_at
*/
class VideoCategory extends \yii\db\ActiveRecord
{
//just gii generated simple code.
}
Now i need to show all the categories of a certian video in video view page.
My question is that how can I do this using Yii2 default methodology.