两个laravel项目有三个数据库

时间:2018-04-28 10:07:12

标签: mysql laravel

两个laravel项目laravel_alaravel_b,它们各自的数据库database_adatabase_b

现在有一些常见数据,我创建了第三个数据库database_common, 这两个项目如何读取第三个数据库?

1 个答案:

答案 0 :(得分:1)

您需要创建额外的数据库连接。试试这样:

config/database.php

'connections' => [

    'common_db' => [
        'driver' => 'mysql',
        'host' => env('COMMON_DB_HOST', ''),
        'port' => env('COMMON_DB_PORT', '3306'),
        'database' => env('COMMON_DB_DATABASE', 'forge'),
        'username' => env('COMMON_DB_USERNAME', 'forge'),
        'password' => env('COMMON_DB_PASSWORD', ''),
        'unix_socket' => env('COMMON_DB_SOCKET', ''),
        'charset' => 'utf8mb4',
        'collation' => 'utf8mb4_unicode_ci',
        'prefix' => '',
        'strict' => true,
        'engine' => null,
    ],

],

.env

COMMON_DB_CONNECTION=mysql
COMMON_DB_HOST=127.0.0.1
COMMON_DB_PORT=3306
COMMON_DB_DATABASE=yourDatabaseName
COMMON_DB_USERNAME=yourDatabaseUsername
COMMON_DB_PASSWORD=yourDatabasePassword

然后你可以像这样编写查询:

$users = DB::connection('common_db')->select(...);

参考:Database: Getting Started。仔细阅读本页。