Get the App
SLTechnology News&Howtos  ›  Development  › 

Example Analysis of Model Table prefix in Yii 2

Shulou Source: shulou.com Published: 2022-06-02 11:48:58 10月06日 Update

This article mainly introduces the sample analysis of the Model table prefix in Yii 2, which has certain reference value. Interested friends can refer to it. I hope you will gain a lot after reading this article. Let Xiaobian take you to understand it together.

1.1 Model Table Prefix

In most systems, a prefix is added to the table name of the database. For example, the table name of the ecshop system has the prefix "ecs_", and the following code is everywhere in their code:

$GLOBALS['ecs']->table('goods')

The purpose of this code is to concatenate the prefix "ecs" with the name that follows to get the actual table name "ecs_goods." Why not just concatenate the strings "ecs_" and "goods"? Because during installation, you can configure the table prefix yourself, so you can't fix the string concatenation here.

In the Yii system, the database table is corresponding to the model, and the table name is returned in the tableName() function of the Model class. In order to handle the problem of table prefix, when returning the table name in this function, you can use code similar to the following:

public static function tableName()

{

return '`user`';

}

As you can see, instead of returning user directly, the table name returned is `user`, replacing % with the table prefix when actually fetching data from the database.

How do I configure the table prefix for my application? Configure it in the db parameter of main.php:

return [

'components' => [

'db' => [

'class' => 'yii\db\Connection',

'dsn' => 'mysql:host=localhost;dbname=liduoo',

'username' => 'root',

'password' => 'mysql',

'charset' => 'utf8',

'tablePrefix' => 'abc_',

],

],

];

Thank you for reading this article carefully. I hope that the article "Example Analysis of Model Table Prefix in Yii 2" shared by Xiaobian will be helpful to everyone. At the same time, I hope that everyone will support you a lot and pay attention to the industry information channel. More relevant knowledge is waiting for you to learn!

Tags: Prefix name code data article database configuration example analysis function character string actual system value system interest parameter and at the same time in the Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Huawei Shulou Technology macOS NVidia OPPO Reno