@EVOSandru6

Почему модель не находит таблицу?

Привет!

Шел по шагам руководства YII2: guide.yii2.org-info.by/guide-ru-start-gii.html ,

После генерации модели CountrySearch ( extends Country) и контроллера CountryController, появилась ошибка при переходе на country/index :

The table does not exist: {{%country_search}}

Используется версия advanced.
namespace app\models;
В классе CountrySearch используются такие пространства имен:
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\Country;

Пробовал исправить на:
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use frontend\models\Country;

Ошибка меняется на:

Unable to find 'frontend\models\Country' in file: S:\DEVELOPER\openserver\OpenServer\domains\yii2/frontend/models/Country.php. Namespace missing?

Вот файлы(все во frontend):

Модель Country:

namespace app\models;

use yii\db\ActiveRecord;

class Country extends ActiveRecord
{
}


Модель CountrySearch:

namespace app\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use frontend\models\Country;

class CountrySearch extends Country
{

    public function rules()
    {
        return [
            [['code', 'name'], 'safe'],
            [['population'], 'integer'],
        ];
    }

    public function scenarios()
    {
        return Model::scenarios();
    }

    public function search($params)
    {
        $query = Country::find();

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params);

        if (!$this->validate()) {
            return $dataProvider;
        }

        $query->andFilterWhere([
            'population' => $this->population,
        ]);

        $query->andFilterWhere(['like', 'code', $this->code])
            ->andFilterWhere(['like', 'name', $this->name]);

        return $dataProvider;
    }
}


Контроллер CountrController:

namespace frontend\controllers;

use Yii;
use app\models\Country;
use app\models\CountrySearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * CountryController implements the CRUD actions for Country model.
 */
class CountryController extends Controller
{
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }

    /**
     * Lists all Country models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new CountrySearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
             'searchModel' => $searchModel,
             'dataProvider' => $dataProvider,
         ]);
    }

    /**
     * Displays a single Country model.
     * @param string $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Country model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Country();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->code]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing Country model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->code]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing Country model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Country model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return Country the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Country::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
  • Вопрос задан
  • 4804 просмотра
Решения вопроса 2
@matperez
Имя таблицы берется из статического метода tableName(). Если он в модели не определен, Yii пытается сгенерировать имя таблицы самостоятельно, что у вас и происходит.
Странно, что у вас модель Country получилась пустая. Допишите имя таблицы и все заработает.
/**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'country';
    }
Ответ написан
Комментировать

Пробовал исправить на:
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use frontend\models\Country;


Это вы зря сделали. У вашей модели Country указан namespace app\models, а вы пытаетесь подключить ее из namespace frontend\models. Исправьте в CountrySearch строку
use frontend\models\Country;
на
use app\models\Country;

По поводу первоначальной ошибки.
Вам нужно добавить в CountrySearch метод
public function tableName()
{
      return 'country';
}


Это связано с тем, что Yii2 при отсутствии этого метода в производном классе (CountrySearch), в качестве имени таблицы модели используется результат этого метода

public static function tableName()
{
        return '{{%' . Inflector::camel2id(StringHelper::basename(get_called_class()), '_') . '}}';
}
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы