首页 > 代码库 > 使用laravel框架的eloquent模型连接多个数据库

使用laravel框架的eloquent模型连接多个数据库

1、配置.env文件

DB_HOST_TRAILER=127.0.0.1
DB_PORT_TRAILER=3306
DB_DATABASE_TRAILER=htms_trailer
DB_USERNAME_TRAILER=root
DB_PASSWORD_TRAILER=

DB_HOST_FREIGHT=127.0.0.1
DB_PORT_FREIGHT=3306
DB_DATABASE_FREIGHT=hangli_saas
DB_USERNAME_FREIGHT=root
DB_PASSWORD_FREIGHT=

 2、配置config/database.php

‘mysql_freight‘ => [
            ‘driver‘    => ‘mysql‘,
            ‘host‘      => env(‘DB_HOST_FREIGHT‘, ‘localhost‘),
            ‘database‘  => env(‘DB_DATABASE_FREIGHT‘, ‘forge‘),
            ‘username‘  => env(‘DB_USERNAME_FREIGHT‘, ‘forge‘),
            ‘password‘  => env(‘DB_PASSWORD_FREIGHT‘, ‘‘),
            ‘charset‘   => ‘utf8‘,
            ‘collation‘ => ‘utf8_unicode_ci‘,
            ‘prefix‘    => ‘‘,
            ‘strict‘    => false,
            ‘engine‘    => null,
        ],
        ‘mysql_trailer‘ => [
            ‘driver‘    => ‘mysql‘,
            ‘host‘      => env(‘DB_HOST_TRAILER‘, ‘localhost‘),
            ‘database‘  => env(‘DB_DATABASE_TRAILER‘, ‘forge‘),
            ‘username‘  => env(‘DB_USERNAME_TRAILER‘, ‘forge‘),
            ‘password‘  => env(‘DB_PASSWORD_TRAILER‘, ‘‘),
            ‘charset‘   => ‘utf8‘,
            ‘collation‘ => ‘utf8_unicode_ci‘,
            ‘prefix‘    => ‘‘,
            ‘strict‘    => false,
            ‘engine‘    => null,
        ],

  3、修改model

//添加
protected $connection = mysql_freight;

 

使用laravel框架的eloquent模型连接多个数据库