laravel 多数据库查询

Introduction 介绍
Laravel is a popular PHP framework with powerful functions. One of its important features is the ability to handle multiple databases simultaneously. Using Laravel's comprehensive database tools, developers have the flexibility and scalability to handle complex data requirements, including data migration, replication, and sharding. This article will outline how to use Laravel to manage multiple databases.
configuration 配置
Laravel's database configuration is set in the config/database.php file. By default, there is one connection array, which represents the primary database connection. To add another database connection, simply add another array entry. Each entry should describe the connection details for the database, including the driver, host, database name, username, and password.
Connection 连接
When you want to connect to a specific database, you can use the connection method on the DB facade. For instance, suppose we have a secondary connection named "customers" defined in our configuration file. In that case, we may connect to and perform queries on that database by calling DB::connection('customers')->select(...).
Model 模型
Laravel's Eloquent ORM also makes managing multiple databases easy. To specify which database table a model should utilize, you may define a $connection property on the model. The $connection property indicates which database connection the model should use. By default, Eloquent will utilize the default connection specified in your database configuration file. A simple example of this would be:
```class User extends Model{ / * The connection name for the model. * * @var string */ protected $connection = 'connection-name';}```
Query Builder 查询构建器
The Laravel Query Builder also supports the use of multiple database connections. The Query Builder uses Laravel's DB class, which includes a connection method that accepts a connection name argument. The Query Builder will handle the rest and appropriately call the correct database connection. For instance, suppose we want to execute a query that returns rows from our secondary database connection. In that case, we can use the following syntax:
```DB::connection('connection-name')->table('table-name')->get();```



