In ThinkPHP, configuring a new database separately is mainly done to meet various business needs. When different business requirements arise or when different data needs to be stored in separate databases, configuring a new database becomes crucial. This configuration allows developers to implement read-write separation, which can significantly improve system performance and scalability.
1. Create a new database.php file under the config directory to store the connection configurations for the new database.
2. In the config/database.php file, add the connection configuration for the new database. Here's an example configuration:
return [ // Default database connection configuration 'default' => [ 'type' => 'mysql', 'hostname' => 'localhost', 'database' => 'thinkphp', 'username' => 'root', 'password' => '', 'hostport' => '', 'charset' => 'utf8mb4', 'prefix' => '', ], // New database connection configuration 'new_db' => [ 'type' => 'mysql', 'hostname' => 'localhost', 'database' => 'new_db', 'username' => 'root', 'password' => '', 'hostport' => '', 'charset' => 'utf8mb4', 'prefix' => '', ], ];
In the code example above, default is the default database connection configuration, and new_db is the newly added database configuration. You can modify the fields according to your actual needs.
3. When using the new database, pass the database connection configuration as shown below:
// Use the default connection $user = Db::name('user')->where('id', 1)->find(); // Use the new_db connection configuration to connect to the new database $user = Db::connect('new_db')->name('user')->where('id', 1)->find();
In the example above, by using Db::connect('new_db'), we specify the connection to the new_db database, thus performing operations on the new database.
1. When using the new database connection, do not directly use the Db::name() method. Instead, you must first use Db::connect() to pass the new database connection configuration and then use Db::name() for database operations.
2. The new database connection configuration must be added to the config/database.php file. If not configured, the database cannot be used.
3. The new database configuration can differ from the default configuration, including the database type, hostname, database name, username, password, etc. However, it is essential to ensure the accuracy of the configuration information to avoid connection errors.
By configuring a new database separately, developers can achieve read-write separation, enhancing both system performance and scalability. When configuring the new database, it is important to use Db::connect() to pass the correct connection configuration, rather than directly using Db::name(). Additionally, the configuration in the config/database.php file must be accurate to ensure smooth database connections.