php - 在 Laravel 5.5 中将 mysql json 字段转换为对象

标签 php mysql eloquent laravel-5.5

我在Mysql中有这张表,详细信息列是json类型。 Sample table capture

这是 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_decodeforeach 并从模型中删除 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/

相关文章:

php - SQL 查询不显示每个子类别中的产品

Mysql - 双组依据

php - 使用 Eloquent/Laravel 存储日期

laravel - Eloquent ORM(laravel 5) 是否负责 SQL 注入(inject)?

mysql - 拉拉维尔 : hasManyThrough relation to get many to many table values

php - 使用 AJAX/PHP/mysqli 创建加载更多按钮

php - 无法输出数据库中与两个选择选项相关的行

php - Wamp 已打开但显示 404 Not Found 无法访问任何项目

php - 获取数据时在数组中显示空白输入数组值 Laravel

mysql - 使用 django-mysql 从 JSON 选择不同的值