mongodb 在Laravel中配置`.env`文件[重复]

hs1rzwqc  于 2023-11-17  发布在  Go
关注(0)|答案(2)|浏览(133)

此问题在此处已有答案

How to use multiple databases in Laravel(9个答案)
16天前关门了。
我想在Laravel中的.env文件中配置MySQL和MongoDB连接。如何为两者设置以下参数:
DB_CONNECTION= DB_HOST= DB_PORT= DB_DATABASE= DB_USERNAME= DB_PASSWORD=.

yqkkidmi

yqkkidmi1#

在您的.env中:

# MySQL Database Configuration
DB_CONNECTION=mysql
MYSQL_DB_HOST=127.0.0.1
MYSQL_DB_PORT=3306
MYSQL_DB_DATABASE=my_database
MYSQL_DB_USERNAME=root
MYSQL_DB_PASSWORD=secret_password

个字符
config/database.php中:

'mysql' => [
    'driver' => 'mysql',
    'host' => env('MYSQL_DB_HOST', '127.0.0.1'),
    'port' => env('MYSQL_DB_PORT', '3306'),
    'database' => env('MYSQL_DB_DATABASE', 'forge'),
    'username' => env('MYSQL_DB_USERNAME', 'forge'),
    'password' => env('MYSQL_DB_PASSWORD', ''),
],
'mongodb' => [
    'driver'   => 'mongodb',
    'host'     => env('MONGO_DB_HOST', 'localhost'),
    'port'     => env('MONGO_DB_PORT', 27017),
    'database' => env('MONGO_DB_DATABASE'),
    'username' => env('MONGO_DB_USERNAME'),
    'password' => env('MONGO_DB_PASSWORD'),
    'options'  => [
        'database' => 'admin', 
    ]
],

的字符串
在进行这些更改后,请不要忘记运行php artisan config:cache

xmq68pz9

xmq68pz92#

您可以在config/database.php中定义新的env变量并为mongoDB创建新的连接:

'connections' => [
  // Other connections ...

  'mongodb' => [
        'driver' => 'mongodb',
        'dsn' => 'mongodb+srv://' . env('MONGO_USERNAME') . ':' . env('MONGO_PASSWORD') . '@' . env('MONGO_CLUSTER') . '/' . env('MONGO_DATABASE') . '?retryWrites=true&w=majority',
        'database' => env('MONGO_DATABASE'),
],

字符串

相关问题