ThinkPHP is an open-source, lightweight, object-oriented web development framework based on PHP. It provides rich features and tools that greatly simplify the development process and help developers improve efficiency.
In database design, it is often necessary to differentiate tables by prefixes, especially in multi-tenant systems where each tenant has its own tables. Using prefixes helps to distinguish and manage these tables effectively. This article will explain how to configure and use table prefixes in ThinkPHP.
In ThinkPHP, you can set a global prefix for database tables through the configuration file, usually located in the config directory under the project root and named database.php.
The configuration file contains a prefix option, which specifies the prefix to be added to all table names. By default, this option is an empty string, meaning no prefix is used.
To set a prefix, simply change the prefix value to the desired string, for example:
'prefix' => 'my_',
Once configured, ThinkPHP automatically adds this prefix to table names during database operations, so manual concatenation is unnecessary.
When creating tables, you can specify the table name including the prefix to distinguish tables. For example, to create a user table with the prefix my_, use the following code:
\think\facade\Db::execute("CREATE TABLE `my_user` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`username` VARCHAR(255) NOT NULL,
`password` VARCHAR(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;");
This method clearly separates the user table by prefix, allowing better management of different tables.
You can also specify the prefixed table name when querying data. For example, to query data from the my_user table, use:
\think\facade\Db::name('my_user')->select();
This ensures the query targets the correct prefixed table.
Configuring a table prefix in ThinkPHP facilitates distinguishing tables for multi-tenant systems or different modules. By setting a unified prefix, table creation and querying become straightforward, making the system structure clearer and maintenance easier.