为什么Laravel Dispatcer dispatch()函数不在特定数据库的作业表中创建作业?

发布于 2025-02-10 14:24:09 字数 382 浏览 2 评论 0原文

在派遣作业之前,我有多个数据库和根据某些条件进行切换数据库。对于例如:

if(condition A){
  DB::setDefaultConnection('A');
} else {
  DB::setDefaultConnection('B');
}
dispatch(new CreateNewUser($user))

根据条件,DB连接更改。 当我查询user :: find($ id)之类的内容时,在派遣根据已连接的数据库返回数据的作业之前。 但是问题是,dispatch()在该数据库的作业表中创建一个作业记录,该数据库首先是在连接的。当DB连接更改为另一个时,仍然填充了第一个数据库的作业表。 这是怎么发生的?

I have multiple databases and switching database as per some conditions before dispatching jobs. For eg:

if(condition A){
  DB::setDefaultConnection('A');
} else {
  DB::setDefaultConnection('B');
}
dispatch(new CreateNewUser($user))

And the db connection is changed as per the condition.
As I query something like User::find($id) before dispatching the job which returns data as per the connected database.
But the problem is, the dispatch() create a jobs record in jobs table of that database which was connected at first. When the db connection changed to another, still the first database's jobs table is populated.
How is this happening?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

情魔剑神 2025-02-17 14:24:09

根据评论,请执行以下操作,更改后清除和重新连接:

DB::purge('mysql'); 
//Do whatever you need to do to setup your connection
DB::setDefaultConnection('B');
DB::reconnect('mysql'); 

您要派遣运行异步的工作。您执行的DB更改不是在作业内部执行的。您应该将连接名称作为参数发送到工作:

dispatch(new CreateNewUser($user, $connName))

以及在作业初始化时,请:

    protected $connName;

    public function __construct($user, $connName)
    {
        $this->connName = $connName;
    }

    public function handle()
    {
        DB::setDefaultConnection($this->connName);
        ....
    }

Based on the comment, do the following, purge and reconnect after your change:

DB::purge('mysql'); 
//Do whatever you need to do to setup your connection
DB::setDefaultConnection('B');
DB::reconnect('mysql'); 

The job you are dispatching runs async. That DB change you are performing is not performed inside the Job. You should send the connection name as a parameter to the Job:

dispatch(new CreateNewUser($user, $connName))

and on the Job initialization, do:

    protected $connName;

    public function __construct($user, $connName)
    {
        $this->connName = $connName;
    }

    public function handle()
    {
        DB::setDefaultConnection($this->connName);
        ....
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文