Laravel 6 config()->get('database.connections.mysql') 与 DB:connection() 不匹配 [英] Laravel 6 config()->get('database.connections.mysql') not matching DB:connection()

查看:41
本文介绍了Laravel 6 config()->get('database.connections.mysql') 与 DB:connection() 不匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的本地环境中,我使用多个租户和 Redis(需要身份验证).
为了服务这个项目,我正在使用 Valet.

In my local environment I am working with multiple tenants and Redis (Auth required).
To serve the project I am using Valet.

对于这种情况,我要解决这两个连接:

For this case I am addressing these two connections:

- basic_foo (is defined in my .env)
- tenant_foo (is the one to change to during a request)

直到现在我成功地改变了连接:

Until now I successfully changed the connections like so:

config()->set('database.connections.mysql', 
       array_merge(
        config()->get('database.connections.mysql') , 
        ['database' => 'tenant_foo']
    ); 

问题

但是,现在我发现查询构建器存在问题,保持或回退到基本连接.

Problem

However, now I am seeing an issue with the query builder, keeping or falling back to the basic connection.

运行时得到tenant_foo的预期连接结果(Redis相同)

I get the expected connection results of tenant_foo (same for Redis) when I run

dd(config()->get('database.connections.mysql'));

当我运行时,basic_foo 的结果是错误的但显然是活跃的

I get the wrong but apparently active results of basic_foo when I run

dd(DB::connection()); // returns IlluminateDatabaseMySqlConnection

所以总而言之,应用程序将返回这个 IlluminateDatabaseQueryException

So all in all the app will return this IlluminateDatabaseQueryException

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'basic_foo.table_bar' doesn't exist...

应该在哪里搜索

'tenant_foo.table_bar'

还没有解决问题的事情

  • 重启Redis
  • 重新安装Redis
  • php 工匠配置:缓存
  • php artisan 缓存:清除
  • php artisan route:clear
  • php artisan view:clear
  • php artisan 优化
  • 作曲家转储自动加载
  • 像下面那样简单地将数据库名称更改为 tenant_foo 是不够的,因为配置数组保持与 basic_foo 相同.

    Simply changing the database name to tenant_foo like below is not enough, as the config array remains the same of basic_foo.

    DB::connection()->setDatabaseName('tenant_foo');
    

    想法

    • 我想更改 DB::connection() 的配置数组,但我不知道除了 config->set() 之外的其他方法.
    • 我安装了 Telescope 这会影响数据库连接吗?
    • 还有其他想法吗?
    • Thoughts

      • I want to change the config-array the of DB::connection(), but I don't know another way than the config->set().
      • I installed Telescope could this affect the db connection?
      • Any other ideas?
      • 推荐答案

        要动态更改数据库名称,您应该使用:

        To dynamically change database name you should use:

        DB::disconnect(); 
        Config::set('database.mysql.database', 'tenant_foo'); 
        DB::reconnect();
        

        这篇关于Laravel 6 config()->get('database.connections.mysql') 与 DB:connection() 不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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