我创建了一个 json 字段product_stored
来存储数组数据。
仓库表结构
在仓库模型中,我使用 $casts 来存储数组数据
protected $casts = [
'produce_stored' => 'array'
];
在 WarehouseController 中 - 索引方法
$warehouses = DB::table('warehouses')
->join('regions', 'regions.id', '=', 'warehouses.region_id')
->join('districts', 'districts.id', '=', 'warehouses.district_id')
->join('users', 'users.id', '=', 'warehouses.agent_assigned')
->select(
'warehouses.id',
'warehouses.name as warehouseName',
'warehouses.ownership_type',
'warehouses.capacity',
'warehouses.produce_stored', // json field with array data
'regions.name as regionName',
'districts.name as districtName',
'users.name as agent_assigned',
'warehouses.status'
)
->get();
return view('admin.warehouses.index', compact('warehouses'));
在 Blade View 中
{{ $warehouse->produce_stored }}
这是浏览器中的输出
["1", "2"]
当我尝试循环数组以获取农产品 ID 来加载农产品名称时
@foreach ($warehouse->produceStored as $produce)
{{$produce}}
@endforeach
上面抛出了一个错误
Invalid argument supplied for foreach()
如何从 Produce_stored 字段获取产品 ID?
最佳答案
你有两个选择:
<?php $warehouse->produceStored = json_decode($warehouse->produceStored, false); ?>
然后尝试
@foreach ($warehouse->produceStored as $produce)
{{$produce}}
@endforeach
2- 就像 Autista_z 在评论中所说:
$warehouses = Warehouse::query()
->join('regions', 'regions.id', '=', 'warehouses.region_id')
->join('districts', 'districts.id', '=', 'warehouses.district_id')
->join('users', 'users.id', '=', 'warehouses.agent_assigned')
->select(
'warehouses.id',
'warehouses.name as warehouseName',
'warehouses.ownership_type',
'warehouses.capacity',
'warehouses.produce_stored', // json field with array data
'regions.name as regionName',
'districts.name as districtName',
'users.name as agent_assigned',
'warehouses.status'
)
->get();
注意:如果 Warehouse 不同,请将其替换为您的型号名称...
关于php - 如何将json字段中的数组数据显示到 Blade View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62116515/