php - 如何将json字段中的数组数据显示到 Blade View ?

标签 php laravel

我创建了一个 json 字段product_stored来存储数组数据。

仓库表结构

enter image description here

在仓库模型中,我使用 $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/

相关文章:

php - 使用相同查询从多个表返回用户数

php - 如何在 mysql 数据库和 php 聊天应用程序中更改用户可用性状态

php - 使用带有 ftp 服务器的 postgresql 的复制功能

php - Laravel WKHTMLTOPDF 不工作

php - Laravel:检测是否加载了嵌套关系

javascript - 如何通过一键删除按钮删除选中的项目

php - 无法启动 Laravel,出现 "Base table or view not found"错误

php - 回显 mysql_num_rows 的所有行

php - GKE/运行 php 应用程序/通过 nginx 或 apache 公开?

laravel - 深度嵌套在 Laravel 集合中的搜索值