Laravel 在数据库上执行预定作业

Laravel perform scheduled job on database

这在某种程度上是我当前 laravel 副项目的设计问题。

所以目前我有一个 table,它在一列中存储一个状态值,以及应该更改该状态的日期。不,我想在存储的日期是当前日期时自动更改该状态值。由于 table 将获得更多关于时间的行,因此我必须以重复的方式执行该更改过程。除此之外,我还想对数据执行一些约束检查。

我确定 laravel 有能力做到这一点,但是怎么做呢?

Laravel 有命令和调度程序,将这两者结合起来正是您想要的。

Console\Commands 文件夹中根据您想要的逻辑创建您的命令。你的问题比较稀疏,所以大部分都是伪逻辑,你可以根据你的情况进行调整。

namespace App\Console\Commands;

class StatusUpdater extends Command
{

    protected $signature = 'update:status';

    protected $description = 'Update status on your model';

    public function handle()
    {
        $models = YourModel::whereDate('date', now())->get();

        $models->each(function (YourModel $model) {
            if ($model->status === 'wrong') {
                $model->status = 'new';
                $model->save();
            }
        });
    }
}

对于此命令 运行 每天,您可以使用调度程序来安排给定的命令。转至 Commands\Kernel.php,您将在其中找到 schedule() 方法。

use App\Commands\StatusUpdater;
use Illuminate\Console\Scheduling\Schedule;

    class Kernel extends ConsoleKernel
    {
        protected function schedule(Schedule $schedule)
        {
            $schedule->command(StatusUpdater::class)->daily();
        }
    }
}

要安排工作,您必须将以下命令添加到服务器上的 cronjob。在 Laravel documentation.

中有描述
* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1