如何在Yii2中使用控制台控制器中的模型?

时间:2016-09-13 11:05:59

标签: php yii cron yii2

我在控制台文件夹中创建了控制器文件,如:

<?php
namespace console\controllers;

use Yii;
use yii\console\Controller;
use backend\models\User;

class TestController extends Controller {

    public function actionIndex() {
        echo "cron job  runnning";
        $userDetails = \backend\models\EndUsers::find()->all();

        echo "<pre>";
    print_r($userDetails);
    exit;

   }
}

但是从控制台运行此命令会引发错误,如:

root@user-desktop:/var/www/html/AWCOX/trunk/source/web# php yii test
cron service runnningException 'yii\base\UnknownClassException' with message 'Unable to find 'backend\models\EndUsers' in file: /var/www/html/AWCOX/trunk/source/web/backend/models/EndUsers.php. Namespace missing?' in var/www/html/AWCOX/trunk/source/web/vendor/yiisoft/yii2/BaseYii.php:291

Stack trace:
#0 [internal function]: yii\BaseYii::autoload('backend\models\...')
#1
/var/www/html/AWCOX/trunk/source/web/console/controllers/TestController.php(15): spl_autoload_call('backend\models\...')
#2 [internal function]: console\controllers\TestController->actionIndex()
#3 /var/www/html/AWCOX/trunk/source/web/vendor/yiisoft/yii2/base/InlineAction.php(55): call_user_func_array(Array, Array)
#4 /var/www/html/AWCOX/trunk/source/web/vendor/yiisoft/yii2/base/Controller.php(154): yii\base\InlineAction->runWithParams(Array)
#5 /var/www/html/AWCOX/trunk/source/web/vendor/yiisoft/yii2/console/Controller.php(119): yii\base\Controller->runAction('', Array)
#6 /var/www/html/AWCOX/trunk/source/web/vendor/yiisoft/yii2/base/Module.php(454): yii\console\Controller->runAction('', Array)
#7 /var/www/html/AWCOX/trunk/source/web/vendor/yiisoft/yii2/console/Application.php(180): yii\base\Module->runAction('test', Array)
#8 /var/www/html/AWCOX/trunk/source/web/vendor/yiisoft/yii2/console/Application.php(147): yii\console\Application->runAction('test', Array)
#9 /var/www/html/AWCOX/trunk/source/web/vendor/yiisoft/yii2/base/Application.php(375): yii\console\Application->handleRequest(Object(yii\console\Request))
#10 /var/www/html/AWCOX/trunk/source/web/yii(27): yii\base\Application->run()
#11 {main}

那么在TestContoller中使用/扩展应用程序模型还有其他方法可以从Console运行吗?

1 个答案:

答案 0 :(得分:2)

在Yii2中,如果您想在控制台中使用模型而不是在select A.EmployeeName, Title, Department, EffectiveDate from ( select EmployeeName, EffectiveDate = max(EffectiveDate) from TableA group by EmployeeName ) A inner join ( select EmployeeName, FieldType, FieldValue from TableA ) src pivot ( max(FieldValue) for FieldType in ([Title], [Department]) ) piv on piv.EmployeeName = A.EmployeeName 下创建模型,那么您可以使用该模型。

我在这个网站上找到了这个:

http://latcoding.com/2015/08/27/run-controller-yii2-via-console/

请试一试。