S
S
Sergey delphinpro2022-01-21 20:00:45
Laravel
Sergey delphinpro, 2022-01-21 20:00:45

How can I update (add data) a JSON field?

We have a field in the table

`names` JSON NULL DEFAULT NULL,

I'm trying to update it

DB::table('towns')
  ->where('id', $town['id'])
  ->update([
    'names' => "JSON_MERGE_PATCH(`names`, JSON_OBJECT('$timestamp', '$name'))"
  ]);


I get an error

SQLSTATE[22032]: <<Unknown error>>: 3140 Invalid JSON text: "Invalid value."
 at position 0 in value for column 'towns.names'.
 (SQL: update `towns` set `names` = JSON_MERGE_PATCH(`names`, JSON_OBJECT('1599001255', 'Кэрг')) where `id` = 1225)


But if I execute the same query in heidisql, then it runs normally

UPDATE `towns`
SET
   `names` = JSON_MERGE_PATCH(`names`, JSON_OBJECT('1599001255', 'Кэрг'))
WHERE `id` = 1225


What is my jamb? How can I update a json field using the DB facade (Eloquent and models are not needed here)?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey delphinpro, 2022-01-22
@delphinpro

Decision:

DB::table('towns')
  ->where('id', $town['id'])
  ->update([
    'names' => DB::raw("JSON_MERGE_PATCH(`names`, JSON_OBJECT('$timestamp', '$name'))")
  ]);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question