database - 在 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 个模块,其中一个模块使用相同类型的数据库连接工作正常,但另一个模块的数据库连接工作不正常。谁能告诉我这段代码有什么问题?谢谢。
解决方案
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',
],
],
];
推荐阅读
- file-not-found - 我运行代码,它显示结果然后它立即变成未找到
- python - 在主启动之前启动屏幕中心(加载图像)
- jupyter-lab - 带有 ipyvuetify 的 jupyter Lab NER 可视化工具?
- windows - Powershell Windows ACL
- python - Django pandas 代码在本地工作 - 而不是在远程服务器上工作(“KeyError”)?
- ajax - 成功时,div 仅通过 AJAX 加载一次
- jquery - 无法使用 jQuery 选择器抓取图像
- javascript - 在Node js中登录身份验证时出错
- java - 每当我运行由 java.lang.nullpointerException 引起的应用程序时,我都会收到此错误:findViewbyId(R.id.btn_start)must not be null
- python - Tkinter 窗口浮动在 i3 中,但也适用于 MS-Windows