我有3个表,分别名为“用户,问题和答案”。我从“答案”表中检索了特定问题的所有答案。现在,我需要获得回答问题的所有用户名。
这就是我的控制器现在的样子:
public function show($id)
{
$question['question'] = Question::find($id);
// fetch all answers where answer table question_id == question_id
$question['answers'] = Answer::where('question_id', $question_id)->get();
//fetch user data who answered the question
$question['users'] = ?
return $question;
}
表关系是:
public function questions()
{
return $this->hasMany(Question::class);
}
public function user()
{
return $this->belongsTo(User::class);
}
public function answers()
{
return $this->hasmany(Answer::class);
}
public function question()
{
return $this->belongsTo(Question::class);
}
public function user()
{
return $this->belongsTo(User::class);
}
鉴于我需要:题+问题的所有答案以及回答的用户名。
提前感谢。
您可以急于在问题上加载answers.user
关系。
Question::with('answers.user')->where('id', $id)->first();
将检索:
您可以将动态范围写入User
类,仅当在其关系中发现问题时才检索用户:
public function scopeOfQuestion($query, $questionId)
{
return $query->whereHas('questions', function ($query) use ($questionId) {
$query->where('id', $questionId);
});
}
public function show($id)
{
$question = Question::find($id);
$users = User::ofQuestion($question->getKey())->get();
}