【发布时间】:2019-12-19 14:50:08
【问题描述】:
获取用户的答案,按用户 ID 在页面中的问题,我想为每个用户显示包含他的问题答案的表格
我尝试创建显示页面并在 UserController 中添加显示功能
控制器:
public function show($id)
{
$user = User::find($id);
$user_id = $user->id;
$survey = \App\Survey::pluck('title', 'id')->toArray();
$answers = \App\Answer::where('user_id','=',$user_id)->get();
return view('users.show', compact('user','survey','answers'));
}
查看:
<table class="table">
<thead class="thead-light">
<tr>
<th>{{ __('Question') }}</th>
<th>{{ __('Answers') }}</th>
<th>{{ __('Creation Date') }}</th>
</tr>
</thead>
<tbody>
@foreach($answers as $t)
<tr>
<td> {{ optional($t->survey)->title }} </td>
<td> {{ $t->answer }} </td>
<td> {{$t->created_at}} </td>
</tr>
@endforeach
</tbody>
</table>
答案模型:
class Answer extends Model
{
protected $fillable = ['answer','commentaire','user_id','survey_id','last_ip'];
protected $table = 'answer';
public function survey()
{
return $this->belongsTo('App\Survey', 'survey_id');
}
public function question()
{
return $this->belongsTo(Question::class);
}
public function user()
{
return $this->belongsTo('App\User', 'user_id');
}
}
用户模型:
public function questions()
{
return $this->hasMany(Question::class);
}
public function answers()
{
return $this->hasMany(Answer::class);
}
表格:
我的问题行有空白部分
【问题讨论】:
标签: laravel relationship