Laravel 数据库:连接多个 MySQL 数据库

Posted cd ~/Homestead

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Laravel 数据库:连接多个 MySQL 数据库相关的知识,希望对你有一定的参考价值。

第一步、定义数据库链接

  • .env
DB_CONNECTION_TEST1=test1
DB_HOST_TEST1=192.168.0.1
DB_PORT_TEST1=3306
DB_DATABASE_TEST1=database1
DB_USERNAME_TEST1=password1
DB_PASSWORD_TEST1=123456


DB_CONNECTION_TEST2=test2
DB_HOST_TEST2=192.168.0.2
DB_PORT_TEST2=3306
DB_DATABASE_TEST2=database2
DB_USERNAME_TEST2=password2
DB_PASSWORD_TEST2=654321
  • config/database.php
'test1' => [
	'driver' => 'mysql',
	'url' => env('DATABASE_URL'),
	'host' => env('DB_HOST_TEST1', '127.0.0.1'),
	'port' => env('DB_PORT_TEST1', '3306'),
	'database' => env('DB_DATABASE_TEST1', 'forge'),
	'username' => env('DB_USERNAME_TEST1', 'forge'),
	'password' => env('DB_PASSWORD_TEST1', ''),
	'unix_socket' => env('DB_SOCKET', ''),
	'charset' => 'utf8mb4',
	'collation' => 'utf8mb4_unicode_ci',
	'prefix' => '',
	'prefix_indexes' => true,
	'strict' => true,
	'engine' => null,
	'options' => extension_loaded('pdo_mysql') ? array_filter([
		PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
	]) : [],
],

'test2' => [
	'driver' => 'mysql',
	'url' => env('DATABASE_URL'),
	'host' => env('DB_HOST_TEST2', '127.0.0.1'),
	'port' => env('DB_PORT_TEST2', '3306'),
	'database' => env('DB_DATABASE_TEST2', 'forge'),
	'username' => env('DB_USERNAME_TEST2', 'forge'),
	'password' => env('DB_PASSWORD_TEST2', ''),
	'unix_socket' => env('DB_SOCKET', ''),
	'charset' => 'utf8mb4',
	'collation' => 'utf8mb4_unicode_ci',
	'prefix' => '',
	'prefix_indexes' => true,
	'strict' => true,
	'engine' => null,
	'options' => extension_loaded('pdo_mysql') ? array_filter([
		PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
	]) : [],
],

第二步、连接第二个数据库

1.Schema 表结构更改

在代码迁移时,可以使用 Schema 提供的 connection() 方法:

Schema::connection('test2')->create('some_table', function($table)

    $table->increments('id'):
);

2.Query 数据库查询

  • 查询语句构造器
    public function searchNews($name)
        $search = DB::connection('test1')->table('news')
            ->where('title', 'like', "%".$name."%")
            ->where('description', 'like', "%".$name."%")
            ->orderBy('inputtime', 'desc')
            ->paginate(15);
        $search = $search->appends(array(
            'name'=>$name,
        ));
        return $search;
    

  • 原生语句
public function getUser()
        return DB::connection('test1')->select("select *from user limit 10");

selectOne:return DB::connection('test1')->selectOne
update:return DB::connection('test1')->update
delete:return DB::connection('test1')->delete
insert:return DB::connection('test1')->insert
commit:return DB::connection('test1')->commit
rollBack:return DB::connection('test1')->rollBack
等等

以上是关于Laravel 数据库:连接多个 MySQL 数据库的主要内容,如果未能解决你的问题,请参考以下文章

Laravel 数据库:连接多个 MySQL 数据库

Laravel 数据库:连接多个 MySQL 数据库

Laravel 数据库:连接多个 MySQL 数据库

在laravel中动态连接多个数据库[重复]

Laravel多个数据库PHPUnit [重复]

Laravel 5:处理多个连接和测试