You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
70 lines
2.2 KiB
70 lines
2.2 KiB
<?php
|
|
|
|
namespace App\Console\Commands; // 定义命名空间
|
|
|
|
use App\Models\Product; // 引入 Product 模型
|
|
use Carbon\Carbon; // 引入 Carbon 日期处理库
|
|
use Illuminate\Console\Command; // 引入 Laravel 的 Command 基类
|
|
use Illuminate\Support\Facades\Cache; // 引入 Cache 门面
|
|
|
|
/**
|
|
* 同步商品浏览量命令
|
|
*
|
|
* 该命令用于同步前一天的商品浏览量,并更新数据库中的相关记录。
|
|
*/
|
|
class SyncProductViewCommand extends Command
|
|
{
|
|
/**
|
|
* 控制台命令的名称和签名
|
|
*
|
|
* @var string
|
|
*/
|
|
protected $signature = 'moon:sync-product_view'; // 定义命令的名称和签名
|
|
|
|
/**
|
|
* 控制台命令的描述
|
|
*
|
|
* @var string
|
|
*/
|
|
protected $description = '同步商品浏览量'; // 描述该命令的用途
|
|
|
|
/**
|
|
* 创建一个新的命令实例.
|
|
*
|
|
* @return void
|
|
*/
|
|
public function __construct()
|
|
{
|
|
parent::__construct(); // 调用父类构造函数
|
|
}
|
|
|
|
/**
|
|
* 执行控制台命令
|
|
*
|
|
* 该方法执行同步商品浏览量的逻辑,包括获取前一天的浏览量并更新数据库。
|
|
*
|
|
* @return mixed
|
|
*/
|
|
public function handle()
|
|
{
|
|
// 获取昨天的日期字符串
|
|
$yesterday = Carbon::yesterday()->toDateString(); // 获取昨天的日期,格式为 YYYY-MM-DD
|
|
|
|
// 查询所有今天有浏览量记录的商品
|
|
$products = Product::query()->where('today_has_view', 1)->get(); // 获取所有今天有浏览量的商品
|
|
|
|
// 遍历每个商品并更新浏览量
|
|
$products->map(function (Product $product) use ($yesterday) {
|
|
// 从缓存中取出前一天的浏览量,默认值为 0
|
|
$viewCount = Cache::pull($product->getViewCountKey($yesterday), 0);
|
|
// 更新商品的浏览量
|
|
$product->view_count += $viewCount; // 累加前一天的浏览量
|
|
$product->today_has_view = 0; // 重置今天的浏览量标记
|
|
$product->save(); // 保存更新后的商品信息
|
|
});
|
|
|
|
// 记录系统日志,记录同步操作的信息
|
|
createSystemLog("系统同步{$yesterday}商品浏览量", ['date' => $yesterday]); // 记录同步的日期
|
|
}
|
|
}
|