简体   繁体   English

Laravel eloquant 集合 - 无法将其转换为有效的 json

[英]Laravel eloquant collection - unable to convert it to valid json

I have one laravel eloquant object which i want to convert to JSON to store in MySQL database, i am using below code to convert我有一个 laravel eloquant object 我想将其转换为 JSON 以存储在 Z62A004B95946BB9754A 数据库中

Order::create(['product' => json_encode($cart->product, true)]);

I also tried below我也在下面尝试过

Order::create(['product' => $cart->product->toJson()]);

This code is storing perfectly but with seems invalid json format like below此代码存储完美,但 json 格式似乎无效,如下所示

"{\"id\": 5,\"name\": \"CAPSTER CAP\",\"description\": \"This is the\"}"

but it should be like below但它应该如下所示

{"id": 5,"name": "CAPSTER CAP","description": "This is the"}

You should need to create a text or longText datatype column in MySQL database.您应该需要在 MySQL 数据库中创建一个 text 或 longText 数据类型列。 Then save JSON as a string like this.然后将 JSON 保存为这样的字符串。

Order::create(['product' => json_encode($cart->product->toArray()) ]);

You need to change your migration class's structure.您需要更改迁移类的结构。 Use json data type for the model class eg将 json 数据类型用于 model class 例如

 Schema::create('orders', function (Blueprint $table) {
     $table->increments('id');
     $table->json('product')->nullable();
     $table->timestamps();
 });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM