将自定义字段添加到Laravel排队的作业记录中? [英] Add custom field to Laravel queued job records?

查看:74
本文介绍了将自定义字段添加到Laravel排队的作业记录中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用数据库"驱动程序的可工作的Laravel 5排队的作业类,称为"SendMyEmail".数据库作业"表中已正确填充了此类分派的作业.

I have a working Laravel 5 queued job class called 'SendMyEmail' using the 'database' driver. The database 'jobs' table is filled with such dispatched jobs correctly.

我想在网站上显示这些作业,因此在构建这些作业记录时,我想在自定义字段名称"上添加并保存一个值. (我会将这个名称作为参数传递给SendMyEmail类构造函数.)

I would like to show these jobs on a website and therefore I would like to add and save a value on a custom field called 'name' on these jobs records when they are constructed. (I would pass this name as a parameter to the SendMyEmail class constructor..)

有人知道该怎么做吗?

推荐答案

好的,所以您想保留已排队/已处理作业的历史记录.

Alright so you want to keep a history of queued/processed jobs, right.

自定义数据库字段没有内置支持.

There isn't any built-in support for customizing the database fields.

请参阅:

https://github.com/laravel/framework/blob/7212b1e9620c36bf806e444f6931cf5f379c68ff/src/Illuminate/Queue/DatabaseQueue.php#L170

根据我的理解,这种行为是有意的,因为您不应该真正与原始的工作"表混淆.它旨在无状态工作.这意味着作业记录在处理后立即被删除.

From my understanding this behaviour is intended, because you shouldn't really mess with the original 'jobs' table. It was designed to work stateless. That means that a job record is removed right after it has been processed.

如果要跟踪作业(例如历史记录),则可以只创建一个新的Eloquent模型并将其传递给Jobs构造函数.为了使原始作业和您的历史记录保持同步,这很有用.

If you want to keep track of your jobs (eg. history), you might just create a new Eloquent model and pass it to your jobs constructor. This is useful, in order to keep the original job and your history synchronized.

好吧,我们开始编码吧?

Alright let's start coding, shall we?

创建新迁移:

php artisan make:migration create_jobs_history_table

php artisan make:migration create_jobs_history_table

现在打开该迁移并添加以下列类型.

Now open that migration and add the following column types.

数据库/迁移/ xyz_create_jobs_history_table :

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateJobsHistoryTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('jobs_history', function(Blueprint $table) {

            $table->bigIncrements('id');
            $table->unsignedInteger('user_id');
            $table->string('job', 40);
            $table->integer('status')->default(0);
            $table->timestamps();

            if (Schema::hasColumn('users', 'id'))
            {
                $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            }

        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::disableForeignKeyConstraints();
        Schema::dropIfExists('jobs_history');
        Schema::enableForeignKeyConstraints();
    }
}

说明:

如您所见,我们添加了三个新类型,分别为 user_id 职位状态.

As you can see, we added three new types called user_id, job and status.

user_id 引用用户的实际ID.

The user_id references the actual id of a user.

工作字段只是工作的描述/名称.

The job field is just a description/name of the job.

状态字段代表状态. 0 =尚未处理,1 =完成

The status field represents the status. 0 = Not yet proccessed, 1 = Done


现在我们的迁移已准备就绪,让我们为其定义一个新模型:


Now that our migration is ready, let us define a new model for it:

app/ JobHistory.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class JobHistory extends Model
{
    protected $table = 'jobs_history';

    protected $hidden = [];

}

甜.现在,我们可以在应用程序中轻松地与我们的工作经历进行交互.

Sweet. Now we can easily interact with our job history in our application.

是时候创建工作了.让我们通过使用以下代码来做到这一点:

It is time to create a job. Let's do so by using the following code:

app/Jobs/ ProvisionUser.php

<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;

use App\User;
use App\JobHistory;

class ProvisonUser implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $user;
    protected $history;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(User $user, JobHistory $history)
    {
        $this->user = $user;
        $this->history = $history;

        // Set up our new history record.

        $this->history->user_id = $this->user->id;
        $this->history->job = 'Provison User';
        $this->history->status = 0;

        $this->history->save();
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        // Do other stuff here....

        // Once the job has finished, set history status to 1.
        $this->history->status = 1;
        $this->history->save();
    }
}

说明:

在这里,我们包括了User和JobHistory模型. 在我们的构造函数中,我们需要两个模型,然后我们建立了一个新模型. 历史记录.

Here we included the User and JobHistory models. In our constructor we require both models and we set up a new history record.

现在实际的工作已与我们的新历史记录同步!

The actual job is now synchronized with our new history record!

好.

在处理作业时调用handle()函数. 完成后,我们将状态设置为1.

The handle() function is called while the job is being processed. Here we set the status to 1, once it has finished.

最后,只需在您的控制器中分派作业即可:

And lastly simply dispatch the job in your controller:

<?php

namespace App\Http\Controllers;

use Carbon\Carbon;

use App\User;
use App\JobHistory;
use App\Jobs\ProvisionUser;

class SomeController extends Controller
{
    public function provision()
    {
        $user = User::find(1);

        $job = (new ProvisionUser($user, new JobHistory))
            ->delay(Carbon::now()->addMinutes(1));

        dispatch($job);

        return view('provision');
    }
}

说明:

我们将现有用户和新工作历史传递给构造函数.后 我们派遣了延迟的工作.

We pass an existing user and new job history to the constructor. After that we dispatch the delayed job.

注意:延迟仅用于演示目的.

Note: The delay is just for demonstrational purposes.

打开您的数据库,并检查您的jobs_history表.调度您的作业后,相应的历史记录的状态应为0.一旦工匠队列工作人员处理了该作业,历史记录的状态应为1.

Open up your database and check your jobs_history table. As soon as your job was dispatched, the status of the corresponding history record should be 0. Once the artisan queue worker has processed the job, the history record status should be 1.

我使用Laravel 5.4测试了此设置,并在应用程序中使用了相同的逻辑.

I tested this setup with Laravel 5.4 and I use the same logic in my application.

祝您编程愉快!

这篇关于将自定义字段添加到Laravel排队的作业记录中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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