Use parameter id in model function

How can I get category name within the category view.

I have the following code in my controller that renders my category using the id parameter as the category id.

For example if you go to localhost:8888/advanced/article/category?id=1 will return all posts with category id of 1.

So some how i need to pass the id parameter in the actionCategory or in my view to the model function Category Name.




     public function actionCategory($id)

    {


        $model = new Article();


        $searchModel = new ArticleSearch();


        $query = Article::find()

        ->where(['category' => $id]);





         $dataProvider = new ActiveDataProvider([

                        'query' => $query,

                        ]);


        return $this->render('category', [

            'searchModel' => $searchModel,

            'dataProvider' => $dataProvider,

            'model'=>$model,

        ]);

    }



In my view which renders the single post it uses the model function CategoryName which requires category id but i can not see how it’s past.

Category Name function




   public function getCategoryName($category = null)

    {

        $category = (empty($category)) ? $this->category : $category ;


        if ($category === self::CATEGORY_ECONOMY)

        {

            return Yii::t('app', 'Economy');

        }

        elseif ($category === self::CATEGORY_SOCIETY)

        {

            return Yii::t('app', 'Society');

        }

        else

        {

            return Yii::t('app', 'Sport');

        }

    }



Why don’t you use a relation between category and article?

In Article.php (model)




    // I use categoryRelation name because category has been used to identify category id ( I would have used category_id )


    public function getCategoryRelation()

    {

        // Customer has_many Order via Order.customer_id -> id

        return $this->hasOne(Category::className(), ['category' => 'id']);

    }



Then in your view you can access to category name from article in this way:




$categoryName = $articleModel->categoryRelation->name



I am using the improved advanced template which has the category name in the model file not in the db only thing in the db is in the article table which has a category id field.

OK. Have you solved?

No I am not to sure how to pass the id/parameter to the getCategoryName function in my model, is this something I should do in my controller and then pass to view or is it something I should put in my view.

For example this


<?= $model->CategoryName ?>

in my view displays sport as no category/id is being passed to the function.

If you have model instance, just call categoryName property that it is attached to relations (written in model)

So




$cn = $model->categoryRelation->field_of_category