对单表中的所有项目编号进行上一个月求和及页面显示
1). 当前使用的 Laravel 版本?
Laravel Framework 8.53.0
2). 当前使用的 php 版本?
PHP 8.0.14
3). 当前系统
macOS 12
5). 相关软件版本
MySQL 5.7
2. 问题描述?
data表
id | name | date | number | projectid |
---|---|---|---|---|
1 | 测试1 | 2021-12-9 | 100 | 1 |
2 | 测试2 | 2021-12-9 | 100 | 1 |
3 | 测试3 | 2021-12-9 | 100 | 2 |
4 | 测试4 | 2022-1-14 | 200 | 2 |
projectid 是外键,即为项目编号,一个项目对应data表中的n的数据。每个项目,按照添加顺序依次将数据添加到data表中。
使用上面的表的结构,需要对每个项目中上个一个月的数量进行求和,然后将求和的数据显示到网页页面上。
我尝试使用了Laravel提供的Schedule任务调度功能,
class SumByMonth extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'db:summonth';
/**
* The console command description.
*
* @var string
*/
protected $description = 'SumByMonth';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
$sum = DB::select("select sum(number) from data where PERIOD_DIFF( date_format( now() , '%Y%m' ) , date_format( date, '%Y%m' ) ) =1 ");
return 0
}
然后在kernel中使用函数调用,每月1日0点进行操作。
protected function schedule(Schedule $schedule)
{
$schedule->command('db:summonth')->monthlyOn(1,'0:00');
}
在我的实验下,针对一个项目,就是1个projectID,可以实现对data表中上个月中的数据进行求和显示。
但是在这样的设计下无法做到对data表中的所有projectID 进行上一个月求和显示。
请问社区大佬们是否有更好的解决方案,或者在我设计的基础上,做一些更改就可以完成需求呢?
十分感谢大家
推荐文章: