【发布时间】:2017-11-08 06:34:50
【问题描述】:
这是 OrderDetails 模型
class OrderDetail extends Model
{
protected $casts = [
'details' => 'array',
];
}
这是控制器
class HomeController extends Controller
{
public function index()
{
$result = OrderDetail::where('details->options->size', 'L')
->limit(10)
->get();
return view('home', compact(['result']));
}
}
还有主页视图
@if($result->count())
@foreach($result as $item)
<li>{{ $item->details }}</li>
@endforeach
@endif
我收到这个错误
htmlspecialchars() 期望参数 1 是字符串,给定数组(视图:/***/resources/views/home.blade.php)
但是,如果我从模型中删除 protected $casts[] 它会显示 JSON,我如何将详细信息字段转换为具有 id 的对象> 和 order_id 字段在同一个查询中?
编辑
现在我得到了一个 JSON 到对象的转换,插入 foreach 和 json_decode 并从模型中删除 protected $casts[],有没有更好的方法?
class HomeController extends Controller
{
public function index()
{
$result = OrderDetail::where('details->options->size', 'L')
->limit(10)
->get();
foreach($result as $key => $item){
$result[$key]->details = json_decode($item->details);
}
return view('home', compact('result'));
}
}
【问题讨论】:
-
@KrisRoofe 我之前检查过这个,但是有什么方法可以将 json 字段作为对象来避免刀片中的这种情况 {{ $item->details['options']['大小'] }} ?
-
将其转换为对象。
标签: php mysql eloquent laravel-5.5