D
D
Dmitry Sudarkin2018-07-02 11:54:04
MySQL
Dmitry Sudarkin, 2018-07-02 11:54:04

How to update json data in database?

Hello! I can not figure out how to update the data in the database with the JSON type.
I have data
id | data1
| [{"_id": "1", "name": "Misha", "age": "30"}, {"_id": "2", "name": "Olya", "age": "25 "}]
2 | ...
How to update in line 1, age to 35 for user Olya ?
If there was a non-multidimensional array, this is how it would be done

Section::where([
   "id" => 1,
])->update([
   'data->age' => '35'
]);

But how to update the data in my case? Tell me who knows, I can not understand ...

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Sudarkin, 2018-07-02
@GrozInventor

Everything turned out to be easier ... it
works like this

Section::where([
   "id" => 1
])->update([
   'data->0->age' => '35'
]);

provided that the key is clearly indicated in the data
{"0": {"_id": "1", "name": "Misha", "age": "30"}, "1": {"_id": "2", "name": "Olya", "age": "25"}}

D
Dmitry Entelis, 2018-07-02
@DmitriyEntelis

If you know for sure that you need to update the data for the 2nd user in the array, then JSON_SET will save you.
https://stackoverflow.com/questions/48552009/mysql...
I think there are no functions that would allow you to update age with a comparison of the name field, only if you write your own.
But in general, it looks like an initially crooked database structure.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question