我有以下返回数组的查询 $wines = Wine::all(); //Remove type_id and producer_id foreach ($wines as $wine) { $location = $wine->producer->location; }如果我 echo $wine-> Producer-> location; 这就是我得到的结果;{"city": "Kavadartsi", "address": "29-ти Ноември, бр. 5, Kavadartsi 1430", "country": "Macedonia"}所以我需要的唯一属性是我尝试访问的地址$wine->producer->location->address;但是当我这样做时,我收到以下错误Trying to get property 'address' of non-object如果我将代码更改为$wine->producer->location['address'];错误是:Illegal string offset 'address'
2 回答
白板的微信
TA贡献1883条经验 获得超3个赞
首先这是错误的:$wine->producer->location->['address'];,你可能想这样做$wine->producer->location['address'];。
如果这不起作用,那么查看生产者迁移文件的样子会有很大帮助,但如果我猜它可能是 json 格式的,就像$table->json('location');. 如果是这种情况,那么您可能需要像这样键入强制转换该特定字段:
<?php
class Location extends Model
{
/**
* The attributes that should be cast.
*
* @var array
*/
protected $casts = [
'location' => 'array',
];
}
完成此操作后,您现在可以像这样获取数据:
$wine->producer->location['address'];
慕标5832272
TA贡献1966条经验 获得超4个赞
去掉location后面的箭头:$wine->producer->location['address'];
如果您收到相同的错误,并且数据库中的位置采用 JSON 格式,请对其进行 json_decode:
$location = json_decode($wine->producer->location, true); $address = $location['address'];
- 2 回答
- 0 关注
- 122 浏览
添加回答
举报
0/150
提交
取消