繁体   English   中英

Php - Laravel:按日期分组的行的总和

[英]Php - Laravel :Sum of rows in group by date

我有数据: 在此处输入图片说明

我想通过特定的 created_at 获得每行总和的结果。 例如,“2020-10-12”日期的人工、租金等总和。

我试过查询,它给了我特定周的数据:

$cashFlowDetails =  CashModel::whereBetween('created_at', [
            now()->locale('en')->startOfWeek()->subWeek() ,
            now()->locale('en')->endOfWeek()->subWeek() ]) 
             ->get();

您可以在 CashModel 上使用 mutator 并附加一个新列,该列将分别保存每一行的总数。

控制器:

public function index()
{
    return CashModel::whereBetween('created_at', [
        now()->locale('en')->startOfWeek()->subWeek(),
        now()->locale('en')->endOfWeek()->subWeek()
    ])->get();
}

模型:

public $appends = ['total_sum'];

public function getTotalSumAttribute($value)
{
    return $this->opening_balance +
        $this->labour +
        $this->rent +
        $this->electricity +
        $this->creditors +
        $this->gst +
        $this->insurance +
        $this->direct_debits +
        $this->other +
        $this->total_amount;
}

输出将是:

[
    {
        "id": 1,
        "labour": 215,
        "rent": 5412,
        "electricity": 1652,
        "creditors": 845,
        "gst": 161,
        "insurance": 332,
        "direct_debits": 1552,
        "other": 2165,
        "total_amount": 464,
        "created_at": "2020-11-15T00:00:00.000000Z",
        "updated_at": "2020-11-25T00:00:00.000000Z",
        "total_sum": 12798
    },
    {
        "id": 6,
        "labour": 771,
        "rent": 2087,
        "electricity": 1517,
        "creditors": 760,
        "gst": 2947,
        "insurance": 103,
        "direct_debits": 4915,
        "other": 4720,
        "total_amount": 2348,
        "created_at": "2020-11-21T04:16:48.000000Z",
        "updated_at": "2020-11-25T04:16:48.000000Z",
        "total_sum": 20168
    }
]

据我了解,您需要每个人工、电力等的日期总计。

下面的查询应该会得到你想要的结果。

$cashFlowDetails = Cash::groupBy('created_at')
    ->selectRaw(
        'created_at,
         sum(labour) as labour,
         sum(rent) as rent,
         sum(electricity) as electricity,
         sum(creditors) as creditors,
         sum(gst) as gst,
         sum(insurance) as insurance,
         sum(direct_debits) as direct_debits,
         sum(others) as others, 
         sum(total_amount) as total_amount',        
    )
    ->whereBetween('created_at', [
        now()->locale('en')->startOfWeek()->subWeek() ,
        now()->locale('en')->endOfWeek()->subWeek() ])
    ->get();

SUM(larbour) 作为 sum_labour,SUM(rent) 作为 sum_rent,等等。

DB::table('table_name')
  ->select(DB::raw('SUM(labour) as sum_labour, DATE(created_at) as created_date'))
  ->groupBy(DB::raw('DATE(created_at)'))
  ->get();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM