donglian6625 2019-05-01 11:57
浏览 46

是否可以在database.php文件中使用Session :: get()方法?

I am Abdullah. I want to use multiple database connection in laravel 5.6. But i want change the database dynamically. best way for me the using Session::get() method in config/database.php.

'connections' => [

    'mysql' => [
        'driver' => 'mysql',
        'host' => env('DB_HOST', '127.0.0.1'),
        'port' => env('DB_PORT', '3306'),
        'database' => env('DB_DATABASE', 'default_db'),
        'username' => env('DB_USERNAME', 'root'),
        'password' => env('DB_PASSWORD', ''),
        'unix_socket' => env('DB_SOCKET', ''),
        'charset' => 'utf8mb4',
        'collation' => 'utf8mb4_unicode_ci',
        'prefix' => '',
        'strict' => true,
        'engine' => null,
    ],

    'mysql2' => [
    'driver' => 'mysql',
    'host' => env('DB_HOST', '127.0.0.1'),
    'port' => env('DB_PORT', '3306'),
    'database' => 'changeable_db',
    'username' => env('DB_USERNAME', 'root'),
    'password' => env('DB_PASSWORD', ''),
    'unix_socket' => env('DB_SOCKET', ''),
    'charset' => 'utf8mb4',
    'collation' => 'utf8mb4_unicode_ci',
    'prefix' => '',
    'strict' => true,
    'engine' => null,
],

],

I want to change the changeable database by using Session::get('db') method. is it possible or any other way?

  • 写回答

1条回答 默认 最新

  • dongyuan8024 2019-05-02 08:08
    关注

    I don't think that is possible because when you change any configuration in your config file and use php artisan to serve you application. You have to stop the running serve and restart It for laravel to take in consideration new configuration. Laravel doesn't hot reload configuration.

    My advice is to define many connection inside the database.php file as you need and when you whan to switch to another connection you can specify it by providing the name of the given connection like this

    $users = DB::connection('connection_name')
        ->table('users')
        ->where('name', 'John')->first();
    

    You can switch connection has you need inside Controller or somewhere else

    If you want to change connection on specific Model you can perform it this way

    $user = new user();
    $user->setConnection('connection_name');
    
    评论

报告相同问题?

悬赏问题

  • ¥15 matlab中使用gurobi时报错
  • ¥15 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂