Các cột JSON trong API Laravel Thêm không chèn
khi tôi thực hiện "thêm" qua POST, json không được chèn. Tôi muốn chèn vào cột "paramJson" một json thông qua api / polls. nhưng nó mang lại cho tôi vấn đề
Tôi có các trường sau:
public function up()
{
Schema::create('polls', function (Blueprint $table) { $table->id();
$table->text('now'); $table->json('paramJson');
$table->enum('status', ['a', 'b', 'c','d'])->default('a');
});
}
Mô hình thăm dò ý kiến:
protected $fillable=[
'now',
];
protected $casts = [
'paramJson' => 'array',
];
PollsController.php
public function add(Request $request)
{
$poll = Poll::create($request->all());
return response()->json($poll, 201);
}
API định tuyến
Route::post('polls','PollsController@add');
Tôi thực hiện cuộc gọi đăng bài http://127.0.0.1:8000/api/polls. nơi tôi gửi một json như sau:
{
"now": "did the MJ12 exist?",
"paramJson" : "{"key1": "value1", "key2": "value2"}"
}
đưa ra lỗi sau: SQLSTATE [HY000]: Lỗi chung: 1364
trong khi nếu tôi chèn nó để nó mất:
{
"now": "did the MJ12 exist?",
"paramJson" : "{\"key1\": \"value1\", \"key2\": \"value2\"}"
}
SQLSTATE [HY000]: Lỗi chung: 1364 Trường 'paramJson'
trong khi nếu tôi chèn nó từ DB, tôi thấy nó như thế này
INSERT INTO polls (now, paramJson) values ("did the MJ12 exist?", '{"key1": "value1", "key2": "value2"}')
"paramJson":"{\"key1\": \"value1\", \"key2\": \"value2\"}",
Nó không thể chèn một json trong laravel như thế này?
Trả lời
Có vẻ như JSON của bạn được mã hóa không chính xác. Thử:
{
"now": "did the MJ12 exist?",
"paramJson" : {
"key1": "value1",
"key2": "value2"
}
}
tức là bỏ dấu ngoặc kép ra khỏi giá trị của paramJson. {"key1": "value1", "key2": "value2"}không phải"{"key1": "value1", "key2": "value2"}"
tôi thay đổi
Mô hình thăm dò ý kiến:
protected $fillable=[ 'now', 'paramJson', ]; protected $casts = [
'paramJson' => 'array',
];
nó hoạt động