【问题标题】:Laravel Eager Load become null in conditional relationshipLaravel Eager Load 在条件关系中变为空
【发布时间】:2021-11-14 16:19:54
【问题描述】:

我在几天后才解决这个问题。

就我而言,有一个学生获得了学者。但是学生桌和学者会员桌是不同的。有停用的学生身份日期。学生每月获得 70 美元,条件是学生仍然活跃,或者如果学生身份停用(辍学/突变到其他学校),但月份的期限小于停用日期。

当经理想看到与停用学生一起接收奖学金的学生时,就会出现问题

型号

student {
   id, student_number, name, status
}

scholar_student {
  id, student_number, start_registered(date), deactivated(date)  
}

关系:

在学者模型中

public function Student() {
   return $this->belongsTo(Student::class,'student_number','student_number')->when($this->status,function($q){
      $q->where('status','active');
   });
}

如何在管理器中获取学生学者名单:

$data = StudentScholar::with('Student')->get();

如果我使用with 添加条件status 的功能总是被跳过。如果我不使用它会查询。如果我不使用with,性能会变得很慢。

有什么想法吗?

【问题讨论】:

    标签: laravel eloquent relationship eager-loading


    【解决方案1】:

    您可以创建两个单独的方法来获取活跃和不活跃的学生。

    public function ActiveStudent(){
       return $this->belongsTo(Student::class,'student_number','student_number')->when($this->status,function($q){
          $q->where('status','active');
       });
    }
    
    public function InactiveStudent(){
       return $this->belongsTo(Student::class,'student_number','student_number')->when($this->status,function($q){
          $q->where('status','inactive');
       });
    }
    

    获取学生列表时

    $data = StudentScholar::with('ActiveStudent','InactiveStudent')->get();

    【讨论】:

      猜你喜欢
      • 2021-05-04
      • 2013-06-20
      • 2017-02-22
      • 1970-01-01
      • 2015-03-01
      • 2021-10-17
      • 2018-09-08
      • 2020-05-23
      • 2018-03-08
      相关资源
      最近更新 更多