我正在使用 Laravel 和 eloquent 以及 mysql 数据库。
我的数据库中有一个 JSON 字段:
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');
}
[...]
当我检索模型/api 路由上的数据时:
Route::middleware('cors:api')->get('/MYROUTE', function (Request $request) {
$resource= Tablex::with('tb1','tb2','tb3')->get();
return $resource->toJson();
});
我的mysql json字段带有字符串格式:
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}",
},
但我需要这种格式:
"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
},
我如何要求 laravel 捕获这种格式的数据?
最佳答案
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
这会将其转换为 PHP 端的数组,并在 Laravel 序列化模型时正确包含 JSON 数据。
关于php - 如何使用 Laravel 将 mysql json 字段转换为 javascript 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53506403/