I
I
Ilya Loopashko2022-01-18 06:31:42
Laravel
Ilya Loopashko, 2022-01-18 06:31:42

How to find the amount by a unique value (date and id) in the database?

I need to find the amount for each day in the database by date and unique id.

Here is my code, but I can't figure out how to find the sum by date, for each day.

iR6qWgx.png

$data = HistoryWeightRecord::get();

$date = [];

foreach ($data as $allDate) {
    $date[] = Carbon::parse($allDate->datetime)->format('Y-m-d');
}

$uniqueDate = collect($date)->unique();

$uniqueEquipment = $data->unique('equipment_id');

$sumArr = [];

foreach ($uniqueEquipment as $eqId) {

    foreach ($uniqueDate as $day) {
        $sum = HistoryWeightRecord::whereDate('datetime', $day)->sum('mass');
        $sumArr[$eqId->equipment_id] = $sum;
    }
}


I want to get this result
$arr = [
            '122' => [
                '2021-01-08' => 207,6
            ],
            '123' => [
                '2021-01-08' => 434,6,
                '2021-01-09' => 233,6,
                '2021-01-10' => 523,6,
            ]
        ];

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ilya Loopashko, 2022-01-18
@deadloop

Understood.

$data = HistoryWeightRecord::get();

        $date = [];
        foreach ($data as $allDate) {
            $date[] = Carbon::parse($allDate->datetime)->format('Y-m-d');
        }
        $uniqueDate = collect($date)->unique();

        $uniqueEquipment = $data->unique('equipment_id');

        $sumArr = [];
        foreach ($uniqueEquipment as $eqId) {
            foreach ($uniqueDate as $day) {
                $sum = HistoryWeightRecord::whereDate('datetime', $day)->where('equipment_id', $eqId->equipment_id)->sum('mass');
                $sumArr[$eqId->equipment_id][$day] = $sum;
            };
        }
        return $sumArr;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question