laravel 操作多数据库总结
读写分离
DB_CONNECTION=mysql
DB_HOST=xxxxxx
DB_PORT=xxx
DB_DATABASE=xx
DB_USERNAME=xxxx
DB_PASSWORD=xxxx
DB_WRITE_CONNECTION=mysql
DB_WRITE_HOST=xxx
DB_WRITE_PORT=3306
DB_WRITE_DATABASE=xxx
DB_WRITE_USERNAME=xx
DB_WRITE_PASSWORD=xxx
'mysql' => [
'driver' => 'mysql',
'database' => 'test',
'username' => 'root',
'password' => 'password',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'strict' => false, // MySQL数据库严格模式,开启后,如果没有默认值会报错,不开启会自动填充一个默认值
'read' => [
[
'host' => '127.0.0.2',
'port' => 3307
],
[
'host' => '127.0.0.3',
'port' => 3308
]
],
'write' => [
'host' => '127.0.0.1',
'port' => 3306,
]
],
- 读、写库选择
- 如果不手动选择的话,数据库会自动判断读写库的选择。
DB::connection('mysql::write')->table('tablename')->find(1); //手动选择写库
DB::connection('mysql::read')->table('tablename')->find(1); //手动选择读库
多数据库
- 默认使用mysql这个数据库
- database.php配置
'mysql1' => [
'driver' => 'mysql',
'host' => env('DB_HOST'),
'port' => env('DB_PORT'),
'database' => env('DB_DATABASE'),
'username' => env('DB_USERNAME'),
'password' => env('DB_PASSWORD'),
'unix_socket' => env('DB_SOCKET'),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'prefix_indexes' => true,
'strict' => true,
'engine' => null,
],
'mysql2' => [
'driver' => 'mysql',
'host' => env('DB_WRITE_HOST' ),
'port' => env('DB_WRITE_PORT'),
'database' => env('DB_WRITE_DATABASE'),
'username' => env('DB_WRITE_USERNAME', 'forge'),
'password' => env('DB_WRITE_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'prefix_indexes' => true,
'strict' => true,
'engine' => null,
],
class OrderFrom extends Model
{
/**
* The table associated with the model.
*
* @var string
*/
protected $connection='mysql2'; //这里设置库
protected $table = 'yd_order_from';
}
- 方式二:可以不再model中配置,在使用的时候,通过$orderFrom->setConnection('mysql2')方法来选择数据库。