【问题标题】:Laravel eloquent relationship 4 table problemLaravel 雄辩关系4表问题
【发布时间】:2020-09-25 18:00:13
【问题描述】:

我的数据库表是

===batches ===
id
batch_title

===courses===
id
course_title
batch_id

===students ===
id
name

===course_student===
course_id
student_id

现在我想显示有多少学生加入了这个批次,还有多少学生参加了这个课程

我的学生模特

public function courses()
{
    return $this->belongsToMany('App\Course');
}

课程模型

public function students(){

            return $this->hasManyThrough('App\Course','App\Student');
        }

    public function batch() {

                return $this->belongsTo('App\Batch','batch_id');
      }

批处理模型

public function courses(){
        return $this->hasOne('App\Course','batch_id');
    }

【问题讨论】:

    标签: laravel eloquent orm relationship


    【解决方案1】:

    你的代码有很多弱点:

    首先应该根据many to many doc重建课程和学生之间的多对多关系

    学生模型

    public function courses()
    {
        return $this->belongsToMany(Course::class);
    }
    

    课程模式

    public function students()
    {
        return $this->belongsToMany(Student::class);
    }
    

    现在:获取本课程有多少学生:

    $value = Course->withCount('students')->find($courseId);
    
    $studentsCount = $value->students_count;
    

    $students_count 将拥有id = $couserId 的课程的学生人数

    如果您想获取特定批次的学生人数,可能会采用相同的方式:

    $coursesInBatch = Course->withCount('students')->where('batch_id',$batchId)->get();
    

    现在$coursesInBatch 持有这批课程,包括students_count

    $studentCountInBatch = 0;
    
    foreach ($coursesInBatch as $course) {
        $studentCountInBatch += $course->students_count;
    }  
    

    现在$studentCountInBatch 将与id($batchId) 一起容纳多少学生

    【讨论】:

      猜你喜欢
      • 2019-03-17
      • 2014-10-18
      • 2015-06-01
      • 1970-01-01
      • 2019-10-29
      • 1970-01-01
      • 2018-07-24
      相关资源
      最近更新 更多