douer9399 2018-07-17 23:33
浏览 194
已采纳

Foreach在laravel中使用不同的查询调用一个数据库表中的值

I want to retrieve values ​​from one database table but separated in two adjacent tables based on different id_produk (foreign key) values.

This is code in Controller :

public function index()
{
  $item_ict  = Item::where('id_produk', '1');
  $item_cm   = Item::where('id_produk', '2');

  return view('item/index', compact('item_ict', 'item_cm'));
}

Then, I call $item_ict and $item_cm in index

<table class="table">
  <thead>
    <tr>
      <th>ICT</th>
      <th>CM</th>
    </tr>
  </thead>
  <tbody>
    @foreach ($item_ict as $itemict)
    @foreach ($item_cm as $itemcm)
    <tr>
      <td>{{ $itemict -> nama_item }}</td>
      <td>{{ $itemcm -> nama_item }}</td>
    </tr>
    @endforeach
    @endforeach
  </tbody>
</table>

is it the correct way when i wrote that foreach? Nothing errors, but no values exited. How the way to fix it?

Or i'm thinking about call it use query in index page, but i dont know how. is it possible? how?

  • 写回答

1条回答 默认 最新

  • doudun5009 2018-07-17 23:41
    关注

    Combine your items into one array so that you only need to do one loop.

    Also, use ->get() to actually get the items. As it stands, your code is still just the query builder.

    public function index()
    {
        $all = [];
        $item_ict = Item::where('id_produk', '1')->get();
        $item_cm = Item::where('id_produk', '2')->get();
    
        for ($i = 0; $i < max($item_ict->count(), $item_cm->count()); $i++) {
            $all[] = [
                isset($item_ict[$i]) ? $item_ict[$i] : null,
                isset($item_cm[$i]) ? $item_cm[$i] : null,
            ];
        }
    
        return view('item/index', compact('all'));
    }
    
    <table class="table">
        <thead>
            <tr>
                <th>ICT</th>
                <th>CM</th>
            </tr>
        </thead>
        <tbody>
            @foreach ($all as $items)
                <tr>
                    <td>{{ $items[0] ? $items[0]->nama_item : null }}</td>
                    <td>{{ $items[1] ? $items[1]->nama_item : null }}</td>
                </tr>
            @endforeach
        </tbody>
    </table>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况
  • ¥15 画两个图 python或R
  • ¥15 在线请求openmv与pixhawk 实现实时目标跟踪的具体通讯方法
  • ¥15 八路抢答器设计出现故障
  • ¥15 opencv 无法读取视频
  • ¥15 按键修改电子时钟,C51单片机
  • ¥60 Java中实现如何实现张量类,并用于图像处理(不运用其他科学计算库和图像处理库))
  • ¥20 5037端口被adb自己占了
  • ¥15 python:excel数据写入多个对应word文档