G. Attila
G. Attila

Reputation: 91

Laravel count how many child elements has every row

I want to make an algorith which calculates how many childs has every row. I have a car model which can have multiple exams. I want to get how many cars have one exam and how many cars have multiple exams. The code I show below takes 21s to execute because I have 10k+ rows.

$cars = Car::get();
$cars->map(function ($item, $key) use (&$recurrent) {
  if($item->exam->count()==1)
  {
     $recurrent['single']++;
  }
  else
  {
     $recurrent['multiple']++;
  }
});

Upvotes: 4

Views: 1447

Answers (2)

G. Attila
G. Attila

Reputation: 91

Thx. for your answer Mozammil, I have corrected your code, and I post it.

$cars = Car::withCount('exam')->get();
$recurrent = array("single" => $cars->where('exam_count', '=', 1)->count(), "multiple" => $cars->where('exam_count', '>', 1)->count());

Upvotes: 1

Mozammil
Mozammil

Reputation: 8750

You would be better off by using Eloquent's withCount. For example, assuming you have a relationship exams in your Car model.

$cars = App\Car::withCount('exams')->get();

foreach ($cars as $car) {
    echo $car->exams_count;
}

If you want to get cars having a certain amount of exams or more, you could do this:

$cars = App\Car::withCount('exams')->get()
    ->having('exams_count', '>', 5)
    ->get();

Upvotes: 3

Related Questions