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>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵