ich eine Datenbankstruktur wie diese haben (zur Vereinfachung):Mit dem() auf variable Ergebnis von Laravel 5 Query Builder
pets table
- id
- name
- owner_id
owners table
- id
- name
- city_id
cities table
- id
- name
Ich möchte die vollständige Liste der Städte mit, neben jedem drucken einer von ihnen, die Anzahl der Haustiere, die dort leben. Dies ist, wie ich versuche, dieses Problem zu nähern:
Diese Funktion meines Controller ist:
// get all pets and associate them with the matching owner record, so every pet has also a city where it lives in.
$pets = DB::table('pets')->join('owners', 'pets.owner_id', '=', 'owners.id')->get();
// get all cities
$cities = DB::table('cities')->get();
// pass values to the view
return View('cities_stats',array('pets'=>$pets, 'cities'=>$cities));
Auf meiner Blade-Vorlage:
@foreach($cities as $city)
<li>
{{ $city->name }}: // city name
{{ $pets->where('city_id', $city->id)->count() }} pets // number of pets in this city
</li>
@endforeach
Das Problem ist, dass es natürlich einen Fehler wirft. Ich kann weder where()
noch count()
in {{ $pets->where('city_id', $city->id)->count() }}
verwenden, weil $pets
ein Array ist.
Was kann ich dann tun?
P.S. Ich benutze Laravel 5.0.