【问题标题】:Laravel : get data for user using relationshipsLaravel:使用关系为用户获取数据
【发布时间】: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


    【解决方案1】:

    您正在执行一些实际上不需要的查询。 首先摆脱这个到行:

     $user_id = $user->id; $survey = \App\Survey::pluck('title', 'id')->toArray();
    

    然后更改您的查询以获得您的答案:

    $answers = \App\Answer::where('user_id','=',$user->id)->with(['survey'])->get();
    return view('users.show', compact('user','answers'));
    

    现在在您看来,您可以这样做:

    <td> {{ $t->survey->title }} </td>
        <td> {{ $t->answer }} </td>
        <td> {{$t->created_at}} </td>
    

    【讨论】:

    • 谢谢,我想 $t->survey->questions->title 但我收到错误
    • 你还没有告诉任何关于 Question 的内容... 然后 $answers = \App\Answer::where('user_id','=',$user->id)->with (['问题'])->get();和 $t->question->title 在你的视图中......
    • 不起作用,答案表:id,survey_id,user_id...,调查表:id,question_id ...问题:id,survey_id,title ...
    猜你喜欢
    • 2016-05-16
    • 2017-07-07
    • 2019-09-12
    • 2017-02-09
    • 2021-05-06
    • 2018-10-24
    • 2022-01-03
    • 2020-11-07
    • 2020-11-06
    相关资源
    最近更新 更多