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 为什么我按照电路图做出的仿真和实物都不能使用
  • ¥15 mars2d在vue3中的引入问题
  • ¥50 h5唤醒支付宝并跳转至向小荷包转账界面
  • ¥15 算法题:数的划分,用记忆化DFS做WA求调
  • ¥15 chatglm-6b应用到django项目中,模型加载失败
  • ¥15 CreateBitmapFromWicBitmap内存释放问题。
  • ¥30 win c++ socket
  • ¥15 C# datagridview 栏位进度
  • ¥15 vue3页面el-table页面数据过多
  • ¥100 vue3中融入gRPC-web