【问题标题】:Convert mysql json field to object in Laravel 5.5在 Laravel 5.5 中将 mysql json 字段转换为对象
【发布时间】:2017-11-08 06:34:50
【问题描述】:

我在Mysql中有这张表,详情栏是json类型。

这是 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 到对象的转换,插入 foreachjson_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'));
    }
}

【问题讨论】:

标签: php mysql eloquent laravel-5.5


【解决方案1】:

compact函数中删除方括号

return view('home', compact('result'));

【讨论】:

  • 我之前试过这个,**htmlspecialchars() ** 错误仍然存​​在。
猜你喜欢
  • 2021-08-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-26
相关资源
最近更新 更多