我正在使用laravel开发一个问题答案应用程序,我想在每个问题下显示该特定问题的所有答案。我面临的问题是我无法改变视图以在相应的问题下显示答案,因为在laravel视图中无法匹配ID!
我的观看代码:
@section('list-questions-answers')
<ul>
@foreach($listQuestions as $q)
<li><a href="{{url('/questions/'.$q->question_id)}}">{{ $q->question }}</a></li>
@foreach($listAnswers as $a)
<ul>
<li>{{ $a->answer }}</li>
</ul>
@endforeach
@endforeach
</ul>
@endsection
答案的模型
public function User()
{
return $this->belongsTo('App\User');
}
public function questions()
{
return $this->belongsTo('App\questions','answer_id');
}
public function scopefetchAnswers($query)
{
return $query->select('answer')->where('people_id','<>',Auth::id())->get();
}
问题的模型:
protected $table='questions';
protected $primaryKey='question_id';
protected $fillable = [
'question', 'created_at','details'
];
//protected $hidden=['question_id'];
public function setUpdatedAtAttribute($value) {}
public function User() {
return $this->belongsTo('App\User');
}
public function answers()
{
return $this->hasMany('App\answers','question_id');
}
public function scopefetchQuestions($query) {
return $query->select('question','question_id')->where('people_id','=',Auth::id())->get();
}
所有内容都显示在dashboard.blade.php上,它在仪表板控制器上运行
class Dashboard extends Controller
{
public function index(){
$listQuestions=questions::latest('created_at')->fetchQuestions();
//$listAnswers=answers::groupBy('question_id')->fetchAnswers();
$listAnswers=answers::fetchAnswers();
return view('forms.question',compact('listQuestions','listAnswers'));
}
}
输出我正在
我想要的输出
答案表
我如何实现输出?我正在使用Laravel 5.2
答案 0 :(得分:1)
您提取问题的查询应为:
$listQuestions= Question::where('people_id', '=', Auth::id())
->with(['answers' => function($q) {
$q->where('people_id', '<>' ,Auth::id());
}])
->get();
您的视图文件应为:
section('list-questions-answers')
<ul>
@foreach($listQuestions as $q)
<li><a href="{{url('/questions/'.$q->question_id)}}">{{ $q->question }}</a></li>
@foreach($q->answers as $a)
<ul>
<li>{{ $a->answer }}</li>
</ul>
@endforeach
@endforeach
</ul>
@endsection