首页 > 解决方案 > 如何检查月份是否变化?

问题描述

我想每月更新所有项目的所有折旧成本,直到 0

例子。

Depriciation has value of 111 . each month it should be depreciated until depriciation cost 
reach 0 or less than 

在此处输入图像描述

控制器

all_item=assets::all();

foreach($all_item as $item)
{
     //should i make static month to compare?

     $month=Carbon::now()->format('m');

     $update_item = assets::findOrFail($item->id);
     $update_item->depriciation_cost = $item->depriciation - $item->depriciation_cost;
     $update_item->update();
}

标签: laravel

解决方案


您可以在表中创建一个新列来跟踪上次更新的折旧值depreciation_updated_at(类型:日期)或使用created_at/updated_at列来获取上次更新月份(如果没有其他原因更新记录)。

然后只需使用代码的更新版本:

all_item=assets::all();

foreach($all_item as $item)
{
   $month=Carbon::now()->format('m');
   $depreciation_updated_at = createFromFormat('Y-m-d', $item->depreciation_updated_at); //or can use created_at/updated_at as said below
   if ($depreciation_updated_at ->format('m') != $month) {
      $update_item = assets::findOrFail($item->id);
      $update_item->depriciation_cost = $item->depriciation - $item->depriciation_cost;
      $update_item->update();
   }
}

希望它能完成你的任务。


推荐阅读