我有这个 SQL 结构来查询学校和男性学生的数量,我正在寻求帮助以将其转换为 laravel eloquent
SELECT *
FROM schools && count(students has(gender == 'male'))
JOIN grades ON (grades.schools = schools.school_id)
JOIN streams ON (stream.schools = schools.school_id)
JOIN students ON (student.schools = schools.school_id)
这就是我在模式学校模式中所做的
Schema::create('schools', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('educationLevel');
$table->foreignId('ward_id')
->constrained('wards')
->onUpdate('cascade');
$table->timestamps();
});
年级
Schema::create('grades', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->foreignId('school_id')->constrained('schools')
->onDelete('cascade');
$table->timestamps();});
溪流
Schema::create('streams', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->foreignId('grade_id')
->constrained('grades')
->onDelete('cascade');
$table->timestamps();
});
学生
Schema::create('students', function (Blueprint $table) {
$table->id();
$table->string('student_name');
$table->string('gender');
$table->foreignId('stream_id')
->constrained('streams')
->onDelete('cascade');
$table->timestamps();
});
这是我之前在学校控制器中尝试过的
$schools = School::select(['name'])->withCount('students')->where('students', function($query){
$query->where('gender', 'male');
})
->get();
在学校模型中,我在下面做了这个
public function grades()
{
return $this->hasMany(Grade::class);
}
public function students(){
return $this->hasManyThrough(Student::class, Stream::class, Grade::class);
}
该模型的关系是一对多的,如下面的学校->有->年级->有->流->学生(性别=男性或女性)
您可以利用addSelect来获得所需的输出
School::query()
->addSelect([
/** Total no of students in school */
'count_students' => Student::selectRaw('count(*)')
->whereIn(
'stream_id',
Stream::select('id')->whereIn(
'grade_id',
Grade::select('id')->whereColumn('school_id', 'schools.id')
)
),
/** Total no of "gender = male" students in school */
'count_male' => Student::selectRaw('count(*)')
->whereRaw('gender = "male"')
->whereIn(
'stream_id',
Stream::select('id')->whereIn(
'grade_id',
Grade::select('id')->whereColumn('school_id', 'schools.id')
)
),
/** Total no of "gender = female" students in school */
'count_female' => Student::selectRaw('count(*)')
->whereRaw('gender = "female"')
->whereIn(
'stream_id',
Stream::select('id')->whereIn(
'grade_id',
Grade::select('id')->whereColumn('school_id', 'schools.id')
)
),
/** Total no of "gender = other" students in school */
'count_other' => Student::selectRaw('count(*)')
->whereRaw('gender = "other"')
->whereIn(
'stream_id',
Stream::select('id')->whereIn(
'grade_id',
Grade::select('id')->whereColumn('school_id', 'schools.id')
)
)
])->get();
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句