Laravel 自定义创建command 命令的使用

生成 Artisan 命令

要创建新命令,您可以使用 make:command Artisan 命令。该命令将在 app/Console/Commands 文件夹中生成一个新的命令类。

进入网站的根目录:要创建新命令,您可以使用 make:command Artisan 命令。该命令将在 app/Console/Commands 文件夹中生成一个新的命令类。

打开终端窗口,输入命令并按回车键创建一个新的工匠命令。

php artisan  make:command BatchUpdateChannelOnlineTotalAmount

上面命令会在App\Console\Commands下面生一个BatchUpdateChannelOnlineTotalAmount.php文件。

在该代码功能里面我们要实现统计销售渠道的总金额。

我们需要修改: $signature,$description 变量的值,目的是为看区分,知道我们这个功能是做什么的。

然后在handle()方法里面写上我们具体的功能代码。

代码写完后,完整代码如下:

<?php

/**
 * 批量更新渠道的销售总额
 * Created by
 * User: yshuq
 * Date: 2022/6/22
 */

namespace App\Console\Commands;

use App\Model\Sales\Order;
use App\Model\Seller\Channel;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class BatchUpdateChannelOnlineTotalAmount extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'update-chanel-online:total-amount';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'batch update channel online total amount';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //根据渠道分组求和来统计渠道的销售总额
        Log::info("批量更新渠道的销售额 开始时间:".date("Y-m-d H:i:s"));
        $order = Order::select("channel_id",
            DB::raw('SUM(base_grand_total) as total_amount'))
            ->where('status','=',Order::ORDER_STATUS_APPROVED)
            ->groupBy('channel_id')
            ->get();

        if(!$order->isEmpty()) {
            $newOrder = [];
            foreach ($order as $key => $item) {
                $newOrder[$key]['id']           = $item['channel_id'];
                $newOrder[$key]['total_amount'] = $item['total_amount'];
                $newOrder[$key]['updated_at']   = Date('Y-m-d H:i:s');
            }

            $index = 'id';
            //批量更新渠道的销售额
            $channelInstance = new Channel;
            Batch()->update($channelInstance, $newOrder, $index);
            Log::info("批量更新渠道的销售额 结束时间:".date("Y-m-d H:i:s"));
        }
    }
}

我们可以将这个命令加入到定时任务里面去执行。

我们需要在Kernel.php里面的$commands数组里面增加下面内容

 protected $commands = [
       ******,
       ******,
       ******,
        \App\Console\Commands\BatchUpdateChannelOnlineTotalAmount::class
    ];

在 schedule方法里面增加定时任务执行的时间

 $schedule->command('update-chanel-online:total-amount')->dailyAt('14:30');

未来验证我们代码功能是否正确,可以手动执行该,命令操作

格式是 php artisan 代码里面的签名,如下:

php artisan update-chanel-online:total-amount