我有数据:

我想通过perticular created_at得到每一行的和的结果。例如,"2020-10-12“日期的劳务量、房租等。
我尝试了查询,得到了perticular week的数据:
$cashFlowDetails = CashModel::whereBetween('created_at', [
now()->locale('en')->startOfWeek()->subWeek() ,
now()->locale('en')->endOfWeek()->subWeek() ])
->get();发布于 2020-11-25 12:02:22
您可以在CashModel上使用一个赋值函数,并追加一个新列,该列将分别保存总共每一行。
控制器:
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
}
]发布于 2020-11-25 12:32:48
据我所知,你需要每个劳动力,电力等的日期合计。
下面的查询应该会得到你想要的结果。
$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();发布于 2020-11-25 12:40:55
SUM(larbour)作为sum_labour,SUM( sum_rent )作为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();https://stackoverflow.com/questions/64997946
复制相似问题