You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel:如何获取并展示多台指定ID设备的相关数据

解决方案

1. 修改控制器代码

首先调整你的控制器逻辑,把拆分后的设备ID用于查询machines表,并将数据传递到视图:

public function ShowProducts(Request $Request){
    $ProductTitle = $Request->id;
    $MillDetails = DB::table('plants')->where('PlantName','=',$ProductTitle)->first();
    $Plants = DB::table('plants')->where('status','=','Active')->get();
    
    // 拆分逗号分隔的ID,同时去除每个ID的空格(避免因空格导致查询失败)
    $machineIds = array_map('trim', explode(',', $MillDetails->Machines));
    
    // 从machines表批量获取对应ID的设备数据
    $machines = DB::table('machines')->whereIn('id', $machineIds)->get();
    
    // 将所有数据传递到视图
    return view('Site.mill', compact('MillDetails', 'Plants', 'machines'));
}

2. 视图中展示设备数据

在resources/views/Site/mill.blade.php中,添加设备数据的展示逻辑(根据你的表结构字段调整):

<!-- 原有展示MillDetails和Plants的代码保留 -->

<h3>关联设备列表</h3>
@if($machines->isNotEmpty())
    <div class="machine-container">
        @foreach($machines as $machine)
            <div class="machine-card">
                <p><strong>设备ID:</strong>{{ $machine->id }}</p>
                <p><strong>设备名称:</strong>{{ $machine->MachineName }}</p>
                <p><strong>设备类型:</strong>{{ $machine->MachineType }}</p>
                <p><strong>产能:</strong>{{ $machine->Capacity }}</p>
                <p><strong>状态:</strong>{{ $machine->status }}</p>
            </div>
        @endforeach
    </div>
@else
    <p>暂无关联设备数据</p>
@endif

关键说明

  • array_map('trim', ...):处理拆分后的ID,避免因逗号后带空格(比如"1, 2,3")导致查询不到对应数据
  • whereIn('id', $machineIds):Laravel查询构造器的批量查询方法,直接匹配数组内的所有ID
  • 视图中用@foreach遍历设备数据,字段名需与machines表的实际字段完全对应

内容的提问来源于stack exchange,提问作者Harish Sharma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 22:48:34