I have a table HouseholdProfile hasMany HouseholdMembers. I want to query all HouseholdProfile with an addional field of how many members of a the specific profile.
What I want:
ID Profile No of Dependents
1 Greg 3 <--- 3 is Number of child record in member table
2 Roger 2
I have tried the query below but I think it lacks something
$query = HouseholdProfile::whereExists(function ($query) {
$query->select(\DB::raw(count('household_members.id')))
->from('household_members')
->whereRaw('household_members.household_profile_id = household_profiles.id');
})
->where('disaster_risk','like','%1%')->get();
If you don't explicitly need an extra column that contains the child count, then you could eager load the relations:
$results = HouseholdProfile::with('household_members')
->where('disaster_risk','like','%1%')
->get();
Then you can access the count for each record in your template like so:
@foreach($results as $row)
{{ $row->household_members->count() }}
@endforeach