laravel - 2 模型 2 foreach 在 1 个 View 中。拉维尔

标签 laravel eloquent

I tried nested foreach few times. but i failed. How to foreach data choices. in duplicates foreach.

Controller

$choices = Choice::where('user_id','=',Auth::id())->get();
$duplicates = Question::selectRaw("count('id') as total, topic_id")->groupBy('topic_id')->get(); 

return view('choices.index',compact('too','choices','duplicates'));

查看

@foreach ($duplicates as $duplicate)
  <tr>
     <td style="text-align: center;">{{ $duplicate->topic->id }}</td>
     <td style="text-align: center;">@foreach ($choices as $choice) {{ $choice->question_number }} @endforeach</td>
 </tr>
@endforeach

我想要的结果是这样的

@foreach ($duplicates as $duplicate)
      <tr>
         <td style="text-align: center;">{{ $duplicate->topic->id }}</td>
         <td style="text-align: center;">$choice->question_number }}</td>
     </tr>
@endforeach

but it cant read that $choice

Link Of picture

最佳答案

从聊天讨论来看,Question模型和Choice模型与Topic模型有关系

您需要像这样定义关系

Topic Model

public function choices(){ 
  return $this->hasMany('App\Choice'); 
}

public function questions(){ 
  return $this->hasMany('App\Question'); 
}

Question Model

public function topic(){ 
   return $this->belongsTo('App\Topic'); 
}

Choice Model

public function topic(){ 
    return $this->belongsTo('App\Topic'); 
}

Now Fetch data

$duplicates = Question::selectRaw("count('id') as total, topic_id")->with('topic', 'topic.choices')->groupBy('topic_id')->get(); 

Template Render

@foreach ($duplicates as $duplicate)
      <tr>
         <td style="text-align: center;">{{ $duplicate->topic->id }}</td>
         <td style="text-align: center;">
               @foreach ($duplicate->topic->choices as $choice)
                 {{ $choice->question_number }}
               @endforeach
         </td>
     </tr>
@endforeach

关于laravel - 2 模型 2 foreach 在 1 个 View 中。拉维尔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50940253/

相关文章:

laravel - 安装编译: tailwind classes not working on fresh install of laravel 6

php - 我的 mysql 查询行出了问题

php - 使用 Eloquent 查找或创建

Laravel:如何从3个有关系的表中获取数据

php - Laravel Eloquent 关系 - 表的多列引用相同的外键

Laravel eloquent中的Mysql按查询求和分组

javascript - 无法在 Laravel 上使用 swal 确认删除

laravel 工作/通知失败

php - 如何在 php 中读取 JsonResponse

php - Laravel 5 Eloquent 递归编程