php - How to convert a mysql json field to a javascript Object with laravel?
问题描述
I'm using laravel with eloquent and a mysql database.
There is a JSON field in my database:
class CreateJogoDetalhesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('tableX', function (Blueprint $table) {
$table->increments('id');
[... others ...]
$table->json('numbers');
}
[...]
When I retrieve the data on my model/api route:
Route::middleware('cors:api')->get('/MYROUTE', function (Request $request) {
$resource= Tablex::with('tb1','tb2','tb3')->get();
return $resource->toJson();
});
My mysql json field comes with a string format:
tableX": {
"id": 1,
"name": "foo",
"values": "{\"6\": 3.5, \"7\": 24.5, \"8\": 24.5, \"9\": 24.5, \"10\": 24.5, \"11\": 24.5, \"12\": 24.5, \"13\": 24.5, \"14\": 24.5, \"15\": 24.5}",
},
But I need them on this format:
"tableX": {
"id": 1,
"name": "foo",
"values": {
"6": 3.5,
"7": 24.5,
"8": 24.5,
"9": 24.5,
"10": 24.5,
"11": 24.5,
"12": 24.5,
"13": 24.5,
"14": 24.5,
"15": 24.5
},
How can I ask to laravel catch the data on this format?
解决方案
The array cast type is particularly useful when working with columns that are stored as serialized JSON. For example, if your database has a JSON or TEXT field type that contains serialized JSON, adding the array cast to that attribute will automatically deserialize the attribute to a PHP array when you access it on your Eloquent model:
class User extends Model
{
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'values' => 'array',
];
}
https://laravel.com/docs/5.7/eloquent-mutators#array-and-json-casting
This will convert it to an array on the PHP side and will properly include the JSON data when Laravel serializes the model.
推荐阅读
- c++ - 在 Eclipse 中使用 libtom/lbtomcrypt
- android - Android ScrollView 奇怪的滚动行为
- javascript - 如何保护原生函数不被 Google API 覆盖
- c# - SelectMany 将查询转换为可枚举列表。如何避免?
- php - 空字节注入仍在 PHP7 中?
- c - 有没有办法为 C 中的类型分配唯一编号?
- python - MultiLabelBinarizer 在逆变换时混淆数据
- c - C 程序不会从 STDIN 读取输入
- nginx - 嵌套在 React 网站中的 VueJs 网站
- java - 如何让 exoplayer 的 ClippingMediaSource 更精确?