我是YII框架中的新手。我已經正確安裝和創建使用Yii的GII擴展測試控制器&測試模型。我在Model中創建了一個方法,並想在Controller中訪問但無法訪問。如何在YII 2框架中調用模型的方法?
測試控制器
<?php
namespace app\controllers\api;
use Yii;
use app\models\api\Test;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
class TestController extends \yii\web\Controller
{
public $modelClass = 'app\models\api\Test';
private $model;
public function filters(){
return array(
'accessControl', // perform access control for CRUD operations
array(
'RestfullYii.filters.ERestFilter +
REST.GET, REST.PUT, REST.POST, REST.DELETE, REST.OPTIONS'
),
);
}
public function actions(){
return array(
'REST.'=>'RestfullYii.actions.ERestActionProvider',
);
}
public function accessRules(){
return array(
array('allow', 'actions'=>array('REST.GET', 'REST.PUT', 'REST.POST', 'REST.DELETE', 'REST.OPTIONS'),
'users'=>array('*'),
),
array('deny', // deny all users
'users'=>array('*'),
),
);
}
protected function loadModel($id = null)
{
if($this->model===null)
{
if($id!==null)
$this->model=TestModel::model()->findByPk($id);
}
return $this->model;
}
public function actionIndex()
{
//return $this->render('index');
//$array = $modelClass::model()->listUserData();
//$array = Yii::app()->model()->listUserData();
//$array = $modelClass->listUserData();
// echo TestModel()->listUserData();
print "<pre>";print_r($this->model->listUserData());
exit;
}
}
測試模型
<?php
namespace app\models\api;
use Yii;
/**
* This is the model class for table "users".
*
* @property integer $id
* @property string $username
* @property string $password
* @property string $email
* @property string $activkey
* @property integer $createtime
* @property integer $lastvisit
* @property integer $superuser
* @property integer $status
*/
class Test extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'users';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['username', 'password', 'email'], 'required'],
[['createtime', 'lastvisit', 'superuser', 'status'], 'integer'],
[['username'], 'string', 'max' => 50],
[['password', 'email', 'activkey'], 'string', 'max' => 128],
[['username'], 'unique'],
[['email'], 'unique'],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'username' => 'Username',
'password' => 'Password',
'email' => 'Email',
'activkey' => 'Activkey',
'createtime' => 'Createtime',
'lastvisit' => 'Lastvisit',
'superuser' => 'Superuser',
'status' => 'Status',
];
}
public static function listUserData(){
$UserData = Test::model()->findAll('status = "0"');
return $UserData;
}
}
我嘗試在論壇搜索,但沒能解決,請你能幫助我解決?
在此先感謝。
感謝您的幫助。我嘗試過,現在方法可以訪問,但看起來像我的模型中的方法有問題。你可以在測試模型中檢查listUserData()方法嗎? – Purushottam