I created CategoryController.php in the controllers folder, everything seems to be writing norms, I cannot display products from the database, it displays the error "http: //site.loc/category/3"

Here is the code in CategoryController.php

<?php namespace app\controllers; use app\models\Category; use app\models\Product; use Yii; class CategoryController extends AppController { public function actionIndex(){ $hits = Product::find()->where(['hit'=>'1'])->limit(4)->all(); $this->setMeta('yiishoptest'); return $this->render('index', compact('hits')); } public function actionView($id){ $id = Yii::$app->request->get('id'); $products = Product::find()->where(['category_id'=>$id])->all(); $category = Category::findOne($id); $this->setMeta ('yiishoptest | . $category->name, $category->keywords, $category->description,'); return $this->render('view', compact('products', 'category')); } } 

and here is the web.php code in the config folder

 'urlManager' => [ 'class' => 'yii\web\UrlManager', 'baseUrl' => '//site.loc', 'enablePrettyUrl' => true, 'showScriptName' => false, 'rules' => [ 'category/<id:\d+>'=> 'category/view', ], 
  • What error does it produce and what kind of animal is it? $this->setMeta - fedornabilkin

1 answer 1

It's not very clear with the $ this-> setMeta call, most likely you don’t need to do that.
And in the controller it would be necessary to restore order. If according to the canons of Yii2, and it makes sense to do so, then you need to add a method for obtaining the model, with a check for its absence.

 protected function findModel($id) { $model = Category::findOne($id); if (!$model) { throw new NotFoundHttpException('The requested page does not exist.'); } return $model; } 

And I would clean up an action to such an extent that it would not obscure any strange lines of code. $ id is not necessary to receive from the request, it will come as an argument.

 public function actionView($id) { $model = Category::findModel($id); $products = $model->products; $this->setMeta ('yiishoptest | . $category->name, $category->keywords, $category->description,'); return $this->render('view', compact('products', 'model')); } 

In addition, the Category model should have a hasMany () association of the type

 public function getProducts() { return $this->hasMany(Products::class, ['category_id' => 'id']); } 

THEN, by getting the Category model, we easily get all the products using $model->products