How to use multiple databases in Laravel

前端 未结 4 1405
清歌不尽
清歌不尽 2020-11-21 23:47

I want to combine multiple databases in my system. Most of the time the database is MySQL; but it may differ in future i.e. Admin can generate such a reports which is

4条回答
  •  情歌与酒
    2020-11-22 00:06

    Laravel has inbuilt support for multiple database systems, you need to provide connection details in config/database.php file

    return [
        'default' => env('DB_CONNECTION', 'mysql'),
    
        'connections' => [
            'mysql' => [
                'driver' => 'mysql',
                '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', ''),
                'charset' => 'utf8',
                'collation' => 'utf8_unicode_ci',
                'prefix' => '',
                'strict' => false,
                'engine' => null,
            ],
    'mysqlOne' => [
                'driver' => 'mysql',
                'host' => env('DB_HOST_ONE', '127.0.0.1'),
                'port' => env('DB_PORT', '3306'),
                'database' => env('DB_DATABASE_ONE', 'forge'),
                'username' => env('DB_USERNAME_ONE', 'forge'),
                'password' => env('DB_PASSWORD_ONE', ''),
                'charset' => 'utf8',
                'collation' => 'utf8_unicode_ci',
                'prefix' => '',
                'strict' => false,
                'engine' => null,
            ],
    ];
    

    Once you have this you can create two base model class for each connection and define the connection name in those models

    //BaseModel.php
    protected $connection = 'mysql';
    
    //BaseModelOne.php
    protected $connection = 'mysqlOne';
    

    You can extend these models to create more models for tables in each DB.

提交回复
热议问题