首页 文章

MYSQL查询到Laravel Eloquent ORM

提问于
浏览
0

嘿,我是新手使用laravel,当我不得不用雄辩的ORM进行一些查询时,我遇到了一些问题 .

我有这样的表:实习,学生和实习_学生(出勤) .

我的数据透视表有一个出勤属性(缺席或现在),我需要实习的ID,并计算每次实习的学生数 .

我有原始查询但我想学习如何使用laravel提供的工具来完成它 .

这是我的原始查询:

DB::table('internship_student')
        ->select(DB::raw('count(*) as real_assistants, internship_id'))
        ->where('attendance', '=', 1)
        ->groupBy('internship_id')
        ->get();

1 回答

  • 1

    根据您的查询,我猜你在 InternshipStudent 之间有 Many to Many 关系 . 基于此,您的模型应如下所示

    Internship Model

    public function students() {
      return $this->belongsToMany('App\Student')->withPivot('attendance');
    }
    

    Student Model

    public function internships() {
      return $this->belongsToMany('App\Internship')->withPivot('attendance');
    }
    

    有了这个,你 should 能够用Eloquent Models调用:

    count($internship->students()->where('attendance', '=', 1)->get());
    

    或者使用Mutator,你可以创建一个自定义属性来获得出勤次数:

    public function getRealAssistantsAttribute() {
       return $this->students()->where('attendance', '=', 1)->get();
    }
    
    //On an Internship instance
    count($internship->real_assistants);
    

    EDIT

    使用Eager Loading的最后一种方法是这样的:

    $internships = Internship::withCount([
      'students as real_attendants' => function($query) {
         $query->where('attendance', '=', 1);
      }
    ])->get();
    

    然后您可以使用以下方式访问它

    $internships[0]->real_attendants_count;
    

相关问题