有时,我们开发项目的时候需要用到多个数据库,在thinkphp中可以使用多个数据库连接,Laravel也可以。Laravel 连接多个数据库及使用方法
配置.env 文件
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=shop DB_USERNAME=root DB_PASSWORD=root DB_HOST_TEST=127.0.0.1 DB_PORT_TEST=3306 DB_DATABASE_TEST=picture_test DB_USERNAME_TEST=root DB_PASSWORD_TEST=root
配置 config/database.php
//默认 'mysql' => [ 'driver' => 'mysql', 'url' => env('DATABASE_URL'), 'host' => env('DB_HOST', '127.0.0.1'), 'port' => env('DB_PORT', '3306'), 'database' => env('DB_DATABASE', 'forge'), 'username' => env('DB_USERNAME', 'forge'), 'password' => env('DB_PASSWORD', ''), 'unix_socket' => env('DB_SOCKET', ''), 'charset' => 'utf8mb4', 'collation' => 'utf8mb4_unicode_ci', 'prefix' => 'lv_', 'prefix_indexes' => true, 'strict' => false, 'engine' => null, 'options' => extension_loaded('pdo_mysql') ? array_filter([ PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'), ]) : [], ], 'picture_test' => [ 'driver' => 'mysql', 'host' => env('DB_HOST_TEST', '127.0.0.1'), 'port' => env('DB_PORT_TEST', '3306'), 'database' => env('DB_DATABASE_TEST', 'picture_test'), 'username' => env('DB_USERNAME_TEST', 'root'), 'password' => env('DB_PASSWORD_TEST', 'root'), 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci', 'prefix' => '', 'strict' => false, ],
model实例(这个model将使用picture_test连接)
<?php namespace App\Model; use Illuminate\Database\Eloquent\Model; class Test extends Model { // 数据库'database_test'中的test表 public $table = 'test'; public $timestamps = false; protected $connection = 'picture_test'; }
调用model实例
// 以下是调用方法 Test::get();
DB直接连接数据库
// 连接picture_test库 DB::connection('picture_test')->table('test')->where('id',1)->first();
文章评论(0)