['class'=>'yii\ db\Connection']"."/> ['class'=>'yii\ db\Connection']".">
search
HomePHP FrameworkYIIHow to connect to the database in yii

How to connect to the database in yii

How does yii connect to the database?

In-depth understanding of connecting to the database in Yii2.0

Yii uses PDO (PHP Date Object) to connect to a variety of databases, therefore, almost all mainstream Yii can provide good support for any database. This is also the broad applicability that a mature framework should have.

Recommended learning: yii framework

Before performing any operation on the database, a connection must be established with the database server. In the Yii application, there is a dedicated core component for handling database connections. We can easily find it in the configuration file:

'components' => [
    'db' => [
        'class' => 'yii\db\Connection',
        'dsn' => 'mysql:host=localhost;dbname=yii2advanced',
        'username' => 'root',
        'password' => '',
        'charset' => 'utf8',
    ],
    // ... ...
],
// ... ...

Someone must have guessed here, Yii uses yii\db \Connection to represent a database connection. This Connection implements a simple encapsulation of PDO, masks the differences between various databases, and implements a unified development interface. In this way, you can ignore most database compatibility issues during the programming process and focus more on functional development. For example, you no longer have to worry about not being able to use Money type fields under MySQL, etc.

Database Schema

When it comes to realizing that Connection is independent of various databases, we have to mention database Schema. Yii provides various mainstream database schemas, and you can even write your own schema to suit your own unique database management system (DBMS). There are several classes related to Schema:

yii\db\Schema abstract class, used to describe the Schema of various DBMSs.

yii\db\TableSchema is used to describe the table structure.

yii\db\ColumnSchema is used to describe field information.

Various schemas under yii\db\pgsql, yii\db\mysql, yii\db\sqlite, yii\db\mssql, yii\db\oci, yii\db\cubird, for specific Describe various DBMS.

In yii\db\Connection, there is a $schemaMap array, which is used to establish the mapping relationship between the PDO database driver and the specific schema class:

public $schemaMap = [
    'pgsql' => 'yii\db\pgsql\Schema', // PostgreSQL
    'mysqli' => 'yii\db\mysql\Schema', // MySQL
    'mysql' => 'yii\db\mysql\Schema', // MySQL
    'sqlite' => 'yii\db\sqlite\Schema', // sqlite 3
    'sqlite2' => 'yii\db\sqlite\Schema', // sqlite 2
    'sqlsrv' => 'yii\db\mssql\Schema', // newer MSSQL driver on MS Windows hosts
    'oci' => 'yii\db\oci\Schema', // Oracle driver
    'mssql' => 'yii\db\mssql\Schema', // older MSSQL driver on MS Windows hosts
    'dblib' => 'yii\db\mssql\Schema', // dblib drivers on GNU/Linux (and maybe other OSes) hosts
    'cubrid' => 'yii\db\cubrid\Schema', // CUBRID
];

We can think that Yii defaults to It supports 10 DBMSs (6 Schemas) in the above array, which is completely sufficient in most cases. In case you use a DBMS beyond this range, you can write a Schema yourself so that Yii can support the DBMS while ensuring compatibility.

Schema base class

yii\db\Schema is an abstract class, and the specific implementation depends on 6 subclasses of Schema for different DBMS. To catch the thief first, catch the king first. When reading the code, read the base class first. Let’s take a look at this yii\db\Schema first:

abstract class Schema extends Object
{
    // 预定义16种基本字段类型,这16种类型是与DBMS无关的,具体到特定的DBMS时,Yii会自动
    // 转换成合适的数据库字段类型。
    const TYPE_PK = 'pk';
    const TYPE_BIGPK = 'bigpk';
    const TYPE_STRING = 'string';
    const TYPE_TEXT = 'text';
    const TYPE_SMALLINT = 'smallint';
    const TYPE_INTEGER = 'integer';
    const TYPE_BIGINT = 'bigint';
    const TYPE_FLOAT = 'float';
    const TYPE_DECIMAL = 'decimal';
    const TYPE_DATETIME = 'datetime';
    const TYPE_TIMESTAMP = 'timestamp';
    const TYPE_TIME = 'time';
    const TYPE_DATE = 'date';
    const TYPE_BINARY = 'binary';
    const TYPE_BOOLEAN = 'boolean';
    const TYPE_MONEY = 'money';
    // 加载表schema,需要子类具体实现
    abstract protected function loadTableSchema($name);
    // ... ...
}

yii\db\Schema. At the beginning, we will focus on the most obvious differences between DBMS. The field data types are unified and 16 basic field types are provided. These 16 types have nothing to do with DBMS. When it comes to a specific DBMS, Yii will automatically convert it into the appropriate database field type. In programming, if we need to specify field types, we use these 16 types. In this case, there is no need to consider whether the specific DBMS used supports it.

You will know what these 16 types mean just by looking at them, so we won’t go into details.

yii\db\Schema::loadTableSchema() is the most important statement in the entire base class. It defines a function for loading the schema of the table, which needs to be implemented by a subclass for a specific DBMS. . Here, we take the yii\db\mysql\Schema subclass as an example to explain:

class Schema extends \yii\db\Schema
{
    // 定义一个数据类型的映射关系
    public $typeMap = [
        'tinyint' => self::TYPE_SMALLINT,
        'bit' => self::TYPE_INTEGER,
        'smallint' => self::TYPE_SMALLINT,
        'mediumint' => self::TYPE_INTEGER,
        'int' => self::TYPE_INTEGER,
        'integer' => self::TYPE_INTEGER,
        'bigint' => self::TYPE_BIGINT,
        'float' => self::TYPE_FLOAT,
        'double' => self::TYPE_FLOAT,
        'real' => self::TYPE_FLOAT,
        'decimal' => self::TYPE_DECIMAL,
        'numeric' => self::TYPE_DECIMAL,
        'tinytext' => self::TYPE_TEXT,
        'mediumtext' => self::TYPE_TEXT,
        'longtext' => self::TYPE_TEXT,
        'longblob' => self::TYPE_BINARY,
        'blob' => self::TYPE_BINARY,
        'text' => self::TYPE_TEXT,
        'varchar' => self::TYPE_STRING,
        'string' => self::TYPE_STRING,
        'char' => self::TYPE_STRING,
        'datetime' => self::TYPE_DATETIME,
        'year' => self::TYPE_DATE,
        'date' => self::TYPE_DATE,
        'time' => self::TYPE_TIME,
        'timestamp' => self::TYPE_TIMESTAMP,
        'enum' => self::TYPE_STRING,
    ];
}

yii\db\mysql\Schema first defines a mapping relationship. This mapping relationship is the field type of the MySQL database and the previous The mapping relationships of the 16 basic data types we mentioned. In other words, based on MySQL Schema, using MySQL field types will be converted into unified 16 basic data types.

Table information (Table Schema)

yii\db\TableSchema class is used to describe the information of the data table:

class TableSchema extends Object
{
    public $schemaName;             // 所属的Schema
    public $name;                   // 表名,不包含Schema部分
    public $fullName;               // 表的完整名称,可能包含一个Schema前缀。
    public $primaryKey = [];        // 主键
    public $sequenceName;           // 主键若使用sequence,该属性表示序列名
    public $foreignKeys = [];       // 外键
    public $columns = [];           // 字段
    // ... ...
}

From the above code See, yii\db\TableSchema is relatively simple. You can roughly understand what they are used for by taking a look at the above attributes. Let’s click a little bit here to understand it.

Column information (Column Schema)

yii\db\ColumnSchema class is used to describe the information of a field, let us take a look:

class ColumnSchema extends Object
{
    public $name;               // 字段名
    public $allowNull;          // 是否可以为NULL
    /**
     * @var string abstract type of this column. Possible abstract types include:
     * string, text, boolean, smallint, integer, bigint, float, decimal, datetime,
     * timestamp, time, date, binary, and money.
     */
    public $type;               // 字段的类型
    /**
     * @var string the PHP type of this column. Possible PHP types include:
     * `string`, `boolean`, `integer`, `double`.
     */
    public $phpType;            // 字段类型对应的PHP数据类型
    /**
     * @var string the DB type of this column. Possible DB types vary according to the type of DBMS.
     */
    public $dbType;
    public $defaultValue;       // 字段默认值
    public $enumValues;         // 若字段为枚举类型,该属性用于表示可供枚举的值
    /**
     * @var integer display size of the column.
     */
    public $size;
    public $precision;          // 若字段为数值,该属性用于表示精度
    /**
     * @var integer scale of the column data, if it is numeric.
     */
    public $scale;
    /**
     * @var boolean whether this column is a primary key
     */
    public $isPrimaryKey;       // 是否是主键
    public $autoIncrement = false;      // 是否是自增长字段
    /**
     * @var boolean whether this column is unsigned. This is only meaningful
     * when [[type]] is `smallint`, `integer` or `bigint`.
     */
    public $unsigned;           // 是否是unsigned,仅对支持的类型有效
    public $comment;            // 字段描述信息
    /**
     * Converts the input value according to [[phpType]] after retrieval from the database.
     * If the value is null or an [[Expression]], it will not be converted.
     * @param mixed $value input value
     * @return mixed converted value
     */
    public function phpTypecast($value)
    {
        if ($value === '' && $this->type !== Schema::TYPE_TEXT && $this->type !== Schema::TYPE_STRING && $this->type !== Schema::TYPE_BINARY) {
            return null;
        }
        if ($value === null || gettype($value) === $this->phpType || $value instanceof Expression) {
            return $value;
        }
        switch ($this->phpType) {
            case 'resource':
            case 'string':
                return is_resource($value) ? $value : (string) $value;
            case 'integer':
                return (int) $value;
            case 'boolean':
                return (bool) $value;
            case 'double':
                return (double) $value;
        }
        return $value;
    }
    /**
     * Converts the input value according to [[type]] and [[dbType]] for use in a db query.
     * If the value is null or an [[Expression]], it will not be converted.
     * @param mixed $value input value
     * @return mixed converted value. This may also be an array containing the value as the first element
     * and the PDO type as the second element.
     */
    public function dbTypecast($value)
    {
        // the default implementation does the same as casting for PHP but it should be possible
        // to override this with annotation of explicit PDO type.
        return $this->phpTypecast($value);
    }
}

The above is the detailed content of How to connect to the database in yii. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Yii's Purpose: Building Web Applications Quickly and EfficientlyYii's Purpose: Building Web Applications Quickly and EfficientlyApr 22, 2025 am 12:07 AM

Yii's purpose is to enable developers to quickly and efficiently build web applications. Its implementation is implemented through the following methods: 1) Component-based design and MVC architecture to improve code maintainability and reusability; 2) Gii tools automatically generate code to improve development speed; 3) Lazy loading and caching mechanism optimization performance; 4) Flexible scalability to facilitate integration of third-party libraries; 5) Provide RBAC functions to handle complex business logic.

Yii's Versatility: From Simple Sites to Complex ProjectsYii's Versatility: From Simple Sites to Complex ProjectsApr 21, 2025 am 12:08 AM

Yiiisversatileavssuitable Projectsofallsizes.1) Simple Sites, YiiOofferseassetupandrapiddevelopment.2) ForcomplexProjects, ITModularityandrbacSystemManagescalabilityandSecurity effective.

Yii and the Future of PHP FrameworksYii and the Future of PHP FrameworksApr 20, 2025 am 12:11 AM

The Yii framework will continue to play an important role in the future development of PHP frameworks. 1) Yii provides efficient MVC architecture, powerful ORM system, built-in caching mechanism and rich extension libraries. 2) Its componentized design and flexibility make it suitable for complex business logic and RESTful API development. 3) Yii is constantly updated to adapt to modern PHP features and technical trends, such as microservices and containerization.

Yii in Action: Real-World Examples and ApplicationsYii in Action: Real-World Examples and ApplicationsApr 19, 2025 am 12:03 AM

The Yii framework is suitable for developing web applications of all sizes, and its advantages lie in its high performance and rich feature set. 1) Yii adopts an MVC architecture, and its core components include ActiveRecord, Widget and Gii tools. 2) Through the request processing process, Yii efficiently handles HTTP requests. 3) Basic usage shows a simple example of creating controllers and views. 4) Advanced usage demonstrates the flexibility of database operations through ActiveRecord. 5) Debugging skills include using the debug toolbar and logging system. 6) Performance optimization It is recommended to use cache and database query optimization, follow coding specifications and dependency injection to improve code quality.

How to display error prompts in yii2How to display error prompts in yii2Apr 18, 2025 pm 11:09 PM

In Yii2, there are two main ways to display error prompts. One is to use Yii::$app->errorHandler->exception() to automatically catch and display errors when an exception occurs. The other is to use $this->addError(), which displays an error when model validation fails and can be accessed in the view through $model->getErrors(). In the view, you can use if ($errors = $model->getErrors())

What are the differences between yi2 and tp5What are the differences between yi2 and tp5Apr 18, 2025 pm 11:06 PM

With the continuous development of PHP framework technology, Yi2 and TP5 have attracted much attention as the two mainstream frameworks. They are all known for their outstanding performance, rich functionality and robustness, but they have some differences and advantages and disadvantages. Understanding these differences is crucial for developers to choose frameworks.

What software is better for yi framework? Recommended software for yi frameworkWhat software is better for yi framework? Recommended software for yi frameworkApr 18, 2025 pm 11:03 PM

Abstract of the first paragraph of the article: When choosing software to develop Yi framework applications, multiple factors need to be considered. While native mobile application development tools such as XCode and Android Studio can provide strong control and flexibility, cross-platform frameworks such as React Native and Flutter are becoming increasingly popular with the benefits of being able to deploy to multiple platforms at once. For developers new to mobile development, low-code or no-code platforms such as AppSheet and Glide can quickly and easily build applications. Additionally, cloud service providers such as AWS Amplify and Firebase provide comprehensive tools

How to limit the rate of Yi2How to limit the rate of Yi2Apr 18, 2025 pm 11:00 PM

The Yi2 Rate Limiting Guide provides users with a comprehensive guide to how to control the data transfer rate in Yi2 applications. By implementing rate limits, users can optimize application performance, prevent excessive bandwidth consumption and ensure stable and reliable connections. This guide will introduce step-by-step how to configure the rate limit settings of Yi2, covering a variety of platforms and scenarios to meet the different needs of users.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor