这是我正在做的事情。
$question = ForumQuestion::where('link',$ques)->with('answers')->first();
$answers = $question->answers;
$answers->load('user');
//return $answers;
return view('forum.question', compact('question','answers'));
CCD_ 1急切地加载该答案的相应用户。
public function user()
{
if ($this->user_type == 'student') {
return $this->belongsTo(Student::class, 'user_id');
}else{
return $this->belongsTo(Teacher::class, 'user_id');
}
}
但问题是$this->user_type得到了某种静态。如果我的第一个答案是user_type = 'teacher'
,那么在每个查询中,它都假设它是teacher
,即使它在一段时间内变为student
。为什么它是静态的?如果我不急于加载,它会很好地工作。
如果您将热切的加载更改为两个不同的类别,而不是将所有内容放在用户函数中,会怎么样
public function student() {
return $this->belongsTo(Student::class, 'user_id');
}
public function teacher() {
return $this->belongsTo(Teacher::class, 'user_id');
}
如果你真的想做一个if语句,可以从不同的函数(比如user)调用它。希望能有所帮助。