一聚教程网:一个值得你收藏的教程网站

热门教程

Laravel同时连接多个数据库的教程

时间:2022-06-29 07:44:28 编辑:袖梨 来源:一聚教程网

这篇文章给大家介绍了多个数据库的实例,方便新手学习,db连接以及model连接。喜欢的话就快来看看吧!

配置.env 文件

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database_name
DB_USERNAME=root
DB_PASSWORD=root

DB_HOST_TEST=127.0.0.1
DB_PORT_TEST=3306
DB_DATABASE_TEST=database_test
DB_USERNAME_TEST=root
DB_PASSWORD_TEST=root

配置 config/database.php

// 默认连接mysql
'default' => env('DB_CONNECTION', 'mysql'),

'connections' => [

 'sqlite' => [
  'driver' => 'sqlite',
  'database' => database_path('database.sqlite'),
  'prefix' => '',
 ],

 'mysql' => [
  'driver' => 'mysql',
  'host' => env('DB_HOST', '127.0.0.1'),
  'port' => env('DB_PORT', '3306'),
  'database' => env('DB_DATABASE', 'database_name'),
  'username' => env('DB_USERNAME', 'root'),
  'password' => env('DB_PASSWORD', 'root'),
  'charset' => 'utf8',
  'collation' => 'utf8_unicode_ci',
  'prefix' => '',
  'strict' => false,
 ],

 'mysql_test' => [
  'driver' => 'mysql',
  'host' => env('DB_HOST_TEST', '127.0.0.1'),
  'port' => env('DB_PORT_TEST', '3306'),
  'database' => env('DB_DATABASE_TEST', 'database_test'),
  'username' => env('DB_USERNAME_TEST', 'root'),
  'password' => env('DB_PASSWORD_TEST', 'root'),
  'charset' => 'utf8',
  'collation' => 'utf8_unicode_ci',
  'prefix' => '',
  'strict' => false,
 ],

 ],

model实例(这个model将使用mysql_test连接)


model实例(这个model将采用默认的'mysql'连接)


调用model实例

// 以下是调用方法
Test::get();
Test::where('id',1)->first();

DB直接连接数据库

// 连接mysql_test库
DB::connection('mysql_test')->table('test')->where('id',1)->first();
// 连接mysql库
DB::connection('mysq')->table('test')->where('id',1)->first();
// 连接mysql库
DB::table('test')->where('id',1)->first();

热门栏目