所以我的数据库上有这种报告表
+---------+------------+-------+
| Company | periods | value |
+---------+------------+-------+
| a1 | 01-01-2018 | 1000 |
| a1 | 01-02-2018 | 600 |
| a2 | 01-01-2018 | 500 |
| a2 | 01-03-2018 | 500 |
| a3 | 01-01-2018 | 500 |
| a3 | 01-02-2018 | 500 |
| a3 | 01-03-2018 | 500 |
+---------+------------+-------+
并且此表与也具有软删除功能的公司表具有belongsTo
关系
+----+------+---------------------+---------------------+
| id | name | created_at | deleted_at |
+----+------+---------------------+---------------------+
| a1 | zzzz | 2018-09-30 08:45:27 | null |
| a2 | xxxx | 2018-03-02 15:35:01 | 2018-02-26 15:35:01 |
| a3 | yyyy | 2018-12-15 14:20:33 | null |
+----+------+---------------------+---------------------+
从question开始,该答案已经有答案。关于这个问题,我想显示每个公司特定时期内的价值总和,这很好。
现在我找到了我需要的另一个要求,这有点复杂,所以从第一个问题继续,例如,当我想要从期间01-02-2018求和时,它会像这样显示(再次已经有上述问题的答案)
+---------+------------+-------+
| Company | periods | value |
+---------+------------+-------+
| a1 | 01-02-2018 | 1600 |
| a2 | 01-02-2018 | 500 |
| a3 | 01-02-2018 | 1000 |
+---------+------------+-------+
这里的问题是,如果我想对期间01-03-2018求和,那么它将仅显示公司a1和a3,因为a2在2018年2月26日被关闭/删除,因此它不属于总和
+---------+------------+-------+
| Company | periods | value |
+---------+------------+-------+
| a1 | 01-03-2018 | 1600 |
| a3 | 01-03-2018 | 1500 |
+---------+------------+-------+
该怎么做?我试图添加报表模型
public function Company()
{
return $this->belongsTo('App\Company','company','id')->where('deleted_at',null);
}
然后是
$sum = Report::with('Company')->addSelect(DB::row('Company, max(periods) AS periods, sum(value) AS value'))
->groupBy('Company')
->where('periods', '<=', $maxDate)
->get();
但是它不起作用。...