这是 OrderDetails 模型
class OrderDetail extends Model
{
protected $casts = [
'details' => 'array',
];
}
这是 Controller
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() expects parameter 1 to be string, array given (View: /***/resources/views/home.blade.php)
但是,如果我从模型中删除 protected $casts[] ,它会向我显示 JSON,我如何将详细信息字段转换为具有 id 的对象> 和 order_id 字段位于同一查询中?
编辑
现在我已经获得了 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'));
关于php - 在 Laravel 5.5 中将 mysql json 字段转换为对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47155681/