我需要在学生表格中获取讲座ID,然后才可以使用该ID获取讲座数据。问题是,当我尝试将其应用于演讲模型时,$ lectureID为null,但是当我在控制台上检查时,它确实获取了数据。预先感谢。
控制器
public function getLecture($id)
{
$lectureID = student::select('lecture_id_FK')->where('student_id',$id)->first();
$lectureDATA = lecture::where('lecture_id',$lectureID)->first();
return $lectureDATA;
}
答案 0 :(得分:0)
you can try two ways
public function getLecture($id)
{
## way 1
$lectureID = student::where('student_id',$id)->value('lecture_id_FK');
$lectureDATA = lecture::where('lecture_id',$lectureID)->first();
## way 2
$lectureID = student::where('student_id',$id)->first();
$lectureDATA = lecture::where('lecture_id',$lectureID->lecture_id_FK)->first();
return $lectureDATA;
}
答案 1 :(得分:0)
在检查$ lectureID内的内容之前:
public function getLecture($id)
{
$lectureID = student::select('lecture_id_FK')->where('student_id',$id)->first();
dd($lectureID);//I believe inside will be object with lecture_id_FK
//then just
$lectureDATA = lecture::where('lecture_id',$lectureID->lecture_id_FK)->first();
return $lectureDATA;
}
推荐的方法:
在学生模型课中(建议使用大写字母S)
class student
{
public function lecture(){
return $this->hasOne('App\lecture','lecture_id_FK','lecture_id');
}
}
然后像这样向学员加载演讲
$student = studend::with('lecture')->find($id);
$lecture = $student->lecture;