简体   繁体   中英

Laravel 4.1 How do get a count of conditional child records, per parent record in an index view?

I have a districts table, which is parent to a locales table. In a district index view, i want to see the number of locales per district that meet a certain criteria.

I'm ok with simple queries and with statements, I get confused when combining multiple methods like the groupBy and count methods.

The following isn't valid syntax, but its how i'm breaking it down in my head.

    $districts = District::all()
                ->with(('locales')
                    ->groupBy('district_id')
                    ->where('validated', '=', 1)
                    ->count())
                ->get();

Expected Output:

District 1 | 27 Locales Validated

District 2 | 15 Locales Validated

District 3 | 14 Locales Validated

I'd like to have access to rest of the districts fields as well. I'm also avoiding the n+1 issue...

Thank you.

You can load your districts with locales (optionally only locals that are validated). Then when you are echoing to the page, you can count the amount of locales.

Your code should probably look something like this:

$districts = District::all()->with(['locales' => function($query) {
    $query->where('validated', '=', 1);
}])->get();

Then when you are echoing to the page:

foreach($districts as $district) {
    echo $district . '|' . $district->locales()->count() . ' Locales Validated';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM