首页 > 解决方案 > 在 yii2 中找不到类 'yii\app\models\DB'

问题描述

我正在尝试在我的模型中使用数据库连接,但它没有连接并抛出错误,因为“找不到类 'app\models\DB'”。我创建了一个通用模型,由模块内的所有模型扩展,这意味着所有模型都扩展了 CommonModel,我在 CommonModel 中收到此错误。我已经阅读了关于数据库连接的 yii 文档并在 Google 上搜索了相同的内容,但我没有找到任何解决方案。我的代码是:

模型\CommonModel.php

namespace app\models;
use Yii;
use yii\base\NotSupportedException;
use yii\db\ActiveRecord;
use yii\helpers\Security;
use yii\web\IdentityInterface;
use yii\db\Query;
use app\models\Mailsettings;
use \PDO as PDO;
class CommonModel extends \yii\db\ActiveRecord{
  protected $_db;
  protected $_sql;
  public function __construct()
  {
    $this->_db = DB::init();  // This line causing the error
    $pdo = Timetrackdb::getPdoConnection(); 
  }
  ----
  ----
}

配置/db.php & 配置/db2.php

return [
  'class' => 'yii\db\Connection',
  'dsn' => 'mysql:host=localhost;dbname=my_db_name',
  'username' => 'db_username',
  'password' => 'db_password',
  'charset' => 'utf8',
];

配置/web.php

$db = require __DIR__ . '/db.php';
$db2 = require __DIR__ . '/db2.php';
$config = [
  'id' => 'basic',
  'basePath' => dirname(__DIR__),
  'bootstrap' => ['log'],
  'modules' => [
     'my_module1' => [
        'class' => 'app\modules\my_module1'
     ],
     'my_module2' => [
        'class' => 'app\modules\my_module2'
     ],
   ],
  ------
  ------
  'db' => $db,
  'db2' => $db2,
  ------
  ------
];

我创建了 2 个模块,其中一个模块使用相同类型的数据库连接工作正常,但另一个模块的数据库连接工作不正常。谁能告诉我这段代码有什么问题?谢谢。

标签: databasemodelyii2

解决方案


Yii 为你处理连接数据库,你不需要PDO. Yii::$app->db2如果您想拥有CommonModel或派生 ActiveRecord 类以使用第二个数据库作为其数据存储,只需访问:

class CommonModel extends ActiveRecord {
    public static function getDb()
    {
        // this will cause Yii to use the database configured as 'db2' in config/web.php
        return Yii::$app->db2;
    }
}

class Car extends CommonModel { }
// will try to insert a new row in `db2`.`car`
(new Car)->save();

如果您要执行跨模式查询 ( config/db2.php),您可能还需要执行以下操作:

return [
  // ...
  // add and adjust the keys below
  'tablePrefix' => '',
  'schemaMap' => [
      'mysql' => [
          'class' => 'yii\db\mysql\Schema',
          'defaultSchema' => 'my_db_name',
      ],
  ],
];

推荐阅读