如何在流明中使用多个数据库 [英] How to use multiple database in Lumen

查看:74
本文介绍了如何在流明中使用多个数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们已经使用Lumen构建API了,现在我们需要访问多个数据库.

We've using Lumen for building API's , Now we need to access multiple databases.

当前使用.env进行数据库配置,但无法在.env

Currently using .env for database config but unable to found the way to multiple databases in .env

我们需要阅读第二连接的地方...

where we need to read 2nd connection ...

推荐答案

首先,您需要配置连接.如果还没有,则需要在项目中创建一个config目录,并添加文件config/database.php.可能看起来像这样:

First, you'll need to configure your connections. If you don't already have one you'll need to create a config directory in your project and add the file config/database.php. It might look like this:

<?php

return [

   'default' => 'accounts',

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

        'mysql2' => [
            'driver'    => 'mysql',
            'host'      => env('DB2_HOST'),
            'port'      => env('DB_PORT'),
            'database'  => env('DB2_DATABASE'),
            'username'  => env('DB2_USERNAME'),
            'password'  => env('DB2_PASSWORD'),
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
            'strict'    => false,
        ],
    ],
];

一旦添加了connection配置,就可以通过从容器中取出数据库管理器对象并调用->connection('connection_name')来访问它们.

Once you've added your connection configurations, you can access them by getting the database manager object out of the container and calling ->connection('connection_name').

// Use default connection
app('db')->connection()->select('xx');
DB::connection()->select('yy');

// Use mysql2 connection
app('db')->connection('mysql2')->select('xx');
DB::connection('mysql2')->select('yy');

希望这对您有帮助!

这篇关于如何在流明中使用多个数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆