【发布时间】:2020-07-04 07:04:53
【问题描述】:
如何使用 eloquent 根据 laravel 中的班级级别计算学生表中的男性、女性和总学生数。我想创造这样的东西;
==================================================
| year | Male | Female | Total |
==================================================
|Level 100 | 60 | 70 | 130 |
|Level 200 | 23 | 20 | 43 |
|Level 300 | 23 | 35 | 58 |
================================================
我试过这个, 这是我的控制器(我从 AppServiceProvider.php 共享数据)
$countgender = DB::table('students')
->select('students.gender', DB::raw('count(*) as total'))
->groupBy('c_level')
->get();
$view->with('gender', $countgender);
下面的刀片模板
<table class="table">
<thead>
<tr>
<th scope="col" width="50%">Year Group</th>
<th scope="col">Male</th>
<th scope="col">Female</th>
<th scope="col">Total</th>
</tr>
</thead>
<tbody>
@foreach($gender as $gender)
<tr>
<th scope="row">{{$gender->c_level}}</th>
<td>{{$gender->total}}</td>
<td>{$gender->total}}</td>
<td></td>
</tr>
@endforeach
</tbody>
</table>
另外,这就是我的表在我的数据库中的结构。
public function up()
{
Schema::create('students', function (Blueprint $table) {
$table->id('std_id');
$table->unsignedBigInteger('student_reference_table');
$table->string('Programme');
$table->string('c_level');
$table->string('image')->nullable();
$table->string('surname');
$table->string('f_name');
$table->string('f_email');
$table->string('DoB');
$table->string('p_address');
$table->string('nationality');
$table->string('region');
$table->string('home_town');
$table->string('phone');
$table->string('mobile');
$table->string('p_school');
$table->string('p_location');
$table->string('disability');
$table->string('gender');
$table->string('fee_category');
$table->string('religion');
$table->string('title');
$table->string('g_surName');
$table->string('g_fname');
$table->string('occupation');
$table->string('gp_address');
$table->string('p_region');
$table->string('g_mobile');
$table->string('g_mail');
$table->string('std_status')->nullable();
$table->timestamps('deleted_at')->nullable();
$table->timestamps();
$table->foreign('student_reference_table')
->references('student_reference')
->on('users')
->onDelete('cascade');
});
}
【问题讨论】:
-
请编辑您的帖子以与示例数据共享表格。您分享的那个没有
c_level或gender列 -
请给我,我只是想知道怎么做
-
请帮助我
-
我正在尝试,但您需要为现有的表结构提供示例数据。您刚刚分享了您的预期输出。
-
请我更新问题
标签: php mysql laravel eloquent