Laravel 如何通过学号获取具体数据?

Laravel how to get count specific data by school id?

下面有 laravel 个查询

$school = DB::table('sekolah')->get();

$morning_session =  DB::table('sekolah')->join('pelajar', 'sekolah.sekolah_id', '=', 'pelajar.sekolah_id') ->where('pelajar.pelajar_sesi', 'like', 'Morning')->groupBy('pelajar.sekolah_id')->count();

$afternoon_session =  DB::table('sekolah')->join('pelajar', 'sekolah.sekolah_id', '=', 'pelajar.sekolah_id')->where('pelajar.pelajar_sesi', 'like', 'Afternoon')->groupBy('pelajar.sekolah_id')->count();

我的blade看起来像这样

@foreach($school as $d) 
    <div class="col-md-6">
        <i class="fa fa-mortar-board" style="font-size:80px;display:block;text-align:center"></i>
         <h4>{{$d->sekolah_nama}}</h4>
         <!-- morning session -->
         <i class="fa fa-calendar" aria-hidden="true"></i> Morning: {{$morning_session}} people
         <!-- afternoon session -->
         <i class="fa fa-calendar" aria-hidden="true"></i>  Afternoon: {{$afternoon_session}}
        </div>
@endforeach

我想为每个学校 ID 计算上午和下午 session。但结果只显示 pelajar.sekolah_id = 1 school website . You can refer my table below at student table

根据我所看到的,您或许可以使用如下方式:

$morning_session =  DB::table('pelajar')
    ->select('sekolah_id', DB::raw('count(*) as total'))
    ->where('pelajar_sesi', 'like', 'Morning')
    ->groupBy('sekolah_id')
    ->pluck('total','sekolah_id')->all();

$afternoon_session =  DB::table('pelajar')
    ->select('sekolah_id', DB::raw('count(*) as total'))
    ->where('pelajar_sesi', 'like', 'Afternoon')
    ->groupBy('sekolah_id')
    ->pluck('total','sekolah_id')->all();

那么在你看来是这样的:

Morning: {{!empty($morning_session[$d->sekolah_id]) ? $morning_session[$d->sekolah_id] : '0'}} people

希望我能理解您的问题,这对您有所帮助。