Blogger Information
Blog 42
fans 5
comment 0
visits 38581
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
laravel 跨表,关联多表调用的优化方案
张浩刚
Original
897 people have browsed it

控制器层中的home.php

  1. <?php
  2. namespace App\Http\Controllers;
  3. use Illuminate\Support\Facades\DB;
  4. class Home extends Controller
  5. {
  6. public function show()
  7. {
  8. //获取文章表的全部信息
  9. $res = DB::table('article')->get()->toArray();
  10. //获取栏目列表名称全部信息
  11. $lister = DB::table('lists')->get()->toArray();
  12. //设置空数组,将栏目数据放入
  13. $cate = [];
  14. //循环栏目对象
  15. foreach($lister as $value){
  16. //空数组的下标就是栏目的id,再增设['title'] 为栏目的title
  17. $cate[$value->id]['title'] = $value->title;
  18. //或者如下,结果同上 ,意思为将对象转换成数组
  19. $cate[$value->id] = (array)$value;
  20. }
  21. //此时空数组 $cate已经放了栏目数组,下标对应栏目id,title对应栏目title
  22. foreach($res as $key=>$value){
  23. //这里将文章内容的二级对象,转换成数组
  24. $res[$key] = (array)$value;
  25. }
  26. //这里的$res 就成为全新的二位数组
  27. //将两个数据全部导入到视图层模板
  28. return view('index', ['index'=>$res, 'lists'=>$cate]);
  29. }
  30. }

视图层: index.blade.php

  1. @foreach($index as $val)
  2. <tr>
  3. <td>{{$val['id']}}</td>
  4. <td>{{$val['title']}}</td>
  5. <!--这里的文章所属栏目list_id作为lists下标,对应的title就是文章所属的栏目名-->
  6. <td>{{$lists[$val['list_id']]['title']}}</td>
  7. </tr>
  8. @endforeach
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post