在yii2中,我有一个用gii工具构建的控制器和模型。但是,当我从控制器调用模型函数时,它会出错。
PHP Fatal Error 'yii\base\ErrorException' with message 'Class 'backend\controllers\TargetCities' not found'
in C:\xampp\htdocs\ncddp\backend\controllers\TargetCitiesController.php:15
Stack trace:
#0 [internal function]: yii\base\ErrorHandler->handleFatalError()
#1 {main}
这是我的控制器.........................................
<?php
namespace backend\controllers;
class TargetCitiesController extends \yii\web\Controller
{
public function actionIndex()
{
return $this->render('index');
}
function actionGetcities()
{
$prov_code = $_POST['prov_code'];
$cities = TargetCities::model()->get_cities($prov_code);
echo $cities;
}
}
这是我的模特...................
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "tbl_target_cities".
*
* @property integer $id
* @property string $city_code
* @property string $kc_classification
* @property integer $cluster
* @property integer $grouping
* @property string $priority
* @property integer $launch_year
*/
class TargetCities extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'tbl_target_cities';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['city_code', 'kc_classification', 'cluster', 'grouping', 'priority', 'launch_year'], 'required'],
[['cluster', 'grouping', 'launch_year'], 'integer'],
[['city_code'], 'string', 'max' => 20],
[['kc_classification', 'priority'], 'string', 'max' => 100],
[['city_code'], 'unique']
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'city_code' => 'City Code',
'kc_classification' => 'Kc Classification',
'cluster' => 'Cluster',
'grouping' => 'Grouping',
'priority' => 'Priority',
'launch_year' => 'Launch Year',
];
}
public function get_cities(){
$select = "SELECT * FROM lib_cities where prov_code=$prov_code";
$query = Yii::app()->db->createCommand($select)->queryAll();
return $query;
}
}
答案 0 :(得分:1)
你丢失的use app\models\TargetCities
。因为您在Php中使用命名空间。如果您没有为use ...
模型Php设置TargetCities
,请在&#39; backend \ controllers&#39;中找到它。命名空间,但它找不到。像这样添加controller
:
use app\models\TargetCities;
class TargetCitiesController extends \yii\web\Controller
{
编辑。
您使用Yii1样式而不是Yii2。在Yii2而不是方法model()
。在控制器中纠正:
function actionGetcities()
{
$prov_code = $_POST['prov_code'];
$cities = TargetCities::get_cities($prov_code);
echo $cities;
}
在模型中TargetCities
将get_cities
声明为static
并将Yii::app()
更改为Yii::$app
,如下所示:
public static function get_cities(){
$select = "SELECT * FROM lib_cities where prov_code=$prov_code";
$query = Yii::$app->db->createCommand($select)->queryAll();
return $query;
}
阅读不同的Yii2和Yii2的文档 - http://www.yiiframework.com/doc-2.0/guide-intro-upgrade-from-v1.html