我如何在 Laravel 中从另一份工作中分派一份工作

Sid*_*rth 7 jobs traits laravel laravel-queue laravel-jobs

Trait method dispatch has not been applied, because there are collisions with other trait methods on 
Run Code Online (Sandbox Code Playgroud)

我总是收到上述错误,现在我想在作业中同时使用 Dispatchable 和 DispatchJobs,我该怎么做?任何帮助或指导将不胜感激。在 Laracasts 上寻找了一些解决方案,但没有一个有效。

Sid*_*rth 6

使用全局dispatch()助手,这将有助于在作业中分派另一个作业。因此,我们根本不需要添加 DispatchesJobs (这消除了与 Dispatchable 的冲突),您只需使用助手dispatch()即可,它就可以工作


小智 4

作业通常不会分派其他作业,因此首先要删除该DispatchJobs特征。您能做的就是监听工作事件

当作业完成时,它会触发该after事件。侦听此事件,然后dispatch()侦听侦听器中的下一个作业:

/**
 * Bootstrap any application services.
 *
 * @return void
 */
public function boot()
{
    Queue::after(function (JobProcessed $event) {
        // determine the job type from $event->job
        // then dispatch the next job based on your logic

        // check the job type
        if ($event->job instanceof MyJob) {
            // get the job payload to pass to next job
            $data = $event->job->payload

            dispatch(new NextJob($data));
            // or use the static method
            NextJob::dispatch($data);
        }
    });
}
Run Code Online (Sandbox Code Playgroud)