繁体   English   中英

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

[英]Foreach to call values from one database table with different query in laravel

我想从一个数据库表中检索值,但根据不同的id_produk(外​​键)值将其分成两个相邻的表。

这是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'));
}

然后,我在索引中调用$ item_ict和$ item_cm

<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>

是我写那个foreach的正确方法吗? 没有任何错误,但没有值退出。 怎么解决呢?

或者我正在考虑使用索引页中的查询来调用它,但是我不知道如何。 可能吗? 怎么样?

将您的项目组合成一个数组,这样您只需要执行一个循环。

另外,使用->get()实际获取项目。 就目前而言,您的代码仍然只是查询生成器。

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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM