Laravel группировка по дате и количеству - PullRequest
1 голос
/ 29 мая 2020

Я пытаюсь добавить дополнительную информацию к Laravel красноречивой коллекции на основе счетного числа поля начала (даты). так что сценарий таков, что у меня есть таблица «встреч», я хочу добавить дополнительные атрибуты к объекту в коллекции, возвращаемой eloquent, если в какие-то дни более 10 встреч. Я пробовал много способов, таких как группировка и счет, но не сработало. в любом случае у меня есть код ниже, и я думаю, что я так близок к нему, но я работал над ним, но не мог найти, как заставить его достичь того, чего я хочу. Я думаю, что застрял и больше не могу думать. Я прокомментировал большинство строк.

        $allAppointments = Appointment::get($columns); //returning all the appointments

        $days = Appointment::get()->groupBy(function ($val) {
                return Carbon::parse($val->start)->format('d');
            }); //here I'm returning appointments by group without the count

        $counter = [];

        foreach ($days as $day => $appointments) {
            foreach ($appointments as $appointment) {

                if (Carbon::parse($appointment->start)->format('d') == $day) {
                    $counter = [Carbon::parse($appointment->start)->format('d') => $day]; //here I'm trying to make an array and count the days but not working
                }
                dd($counter);
                foreach ($allAppointments as $allAppointment) {
                    if (Carbon::parse($allAppointment->start)->format('d') == $day && count($counter) == 10) //here I want to compare the dates and check if that day have more than 10 appointments
                        $allAppointment->setAttribute('backgroundColor', 'red'); //here I want to add the extra information
                }
            }
        }

Ответы [ 3 ]

0 голосов
/ 29 мая 2020

Странно, проработав над ним почти 10 часов, всего через 20 минут после размещения здесь я смог заставить его работать. код ниже:

public function all()
    {
        $columns = [
            'id',
            'title',
            'start',
            'end',
            'note',
            'allDay',
            'editable',
        ];

        $allAppointments = Appointment::get($columns);
        $days = Appointment::get()
            ->groupBy(function ($val) {
                return Carbon::parse($val->start)->format('d');
            });


        foreach ($days as $day => $appointments) {
            foreach ($appointments as $appointment) {
                foreach ($allAppointments as $key => $allAppointment) {
                    if (Carbon::parse($allAppointment->start)->format('d') == $day && $appointments->count() >= 10){
                        $allAppointment->setAttribute('backgroundColor', 'red');
                    }
                }         
            }
        }

        return $allAppointments;
    }
0 голосов
/ 29 мая 2020

Сделайте это

        $allAppointments = Appointment::get($columns); //returning all the appointments

        $days = Appointment::get()->groupBy(function ($val) {
            return Carbon::parse($val->start)->format('d');
        }); //returning appointments by group without the count

        foreach ($days as $day => $appointments) {
            foreach ($appointments as $appointment) {
                $counter = 0;
                if (Carbon::parse($appointment->start)->format('d') == $day) {
                    $counter = count($appointments); //appointments counter
                }
                foreach ($allAppointments as $allAppointment) {
                    if (Carbon::parse($allAppointment->start)->format('d') == $day && $counter >= 10) //compare the date and check if that day have more than 10 appointments
                        $allAppointment->setAttribute('backgroundColor', 'red'); //add the extra information here
                }
            }
        }
0 голосов
/ 29 мая 2020

Попробуйте следующее:

    Appointment::select(DB::raw('if(count(*) > 10, true, false) as more_than_ten_appointment'))->groupBy(function ($val) {
            return Carbon::parse($val->start)->format('d');
        })->get();

если класс DB не существует, добавьте после пространства имен:

use DB;
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...