[英]Convert mysql json field to object in Laravel 5.5
I have this table in Mysql, details column is a json type. 我在Mysql中有此表,详细信息列是json类型。
This is the OrderDetails model 这是OrderDetails模型
class OrderDetail extends Model
{
protected $casts = [
'details' => 'array',
];
}
This is the controller 这是控制器
class HomeController extends Controller
{
public function index()
{
$result = OrderDetail::where('details->options->size', 'L')
->limit(10)
->get();
return view('home', compact(['result']));
}
}
And the home view 和主视图
@if($result->count())
@foreach($result as $item)
<li>{{ $item->details }}</li>
@endforeach
@endif
Im getting this error 我收到这个错误
htmlspecialchars() expects parameter 1 to be string, array given (View: /***/resources/views/home.blade.php)
htmlspecialchars()期望参数1为字符串,给定数组(查看:/ *** / resources / views / home.blade.php)
But if i remove the protected $casts[] from the model it shows me the JSON, how can i convert the details field in to an object having the the id and order_id fields in the same query? 但是,如果我从模型中删除受保护的$ casts [] ,它会向我显示JSON,我如何将详细信息字段转换为同一查询中具有id和order_id字段的对象?
Edit 编辑
Now i have get a JSON to object conversion inserting a foreach
with a json_decode
and removing the protected $casts[]
from the model, is there a better way to this? 现在,我得到了从JSON到对象的转换,插入带有
json_decode
的foreach
并从模型中删除了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'));
}
}
从compact
功能中删除方括号
return view('home', compact('result'));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.