John Davidson

php - How to update JSON field in database with non-primitive value?

0 comments
Message:


The json column in the database has a data like this:


{"data": {"total":15,"time":25}}

This is the data I want to update within it:


{"total":22,"time":5}

But when updating the data via Laravel like this:


$json_data = json_encode(['total' => 22, ...]);
$table->where->update(['column->data' => $json_data])

the result is as follows:


{"data": "{\"total\":22,\"time\":5}"}

When I pass the array without json_encodeing it, it raises an error instead.


How can I assign a non-primitive value directly to a property in a JSON field?



My Answer:
To update a JSON field in a database with a non-primitive value, you can use the `->jsonSet()` method provided by Laravel's Eloquent ORM. Here's an example of how you can update the JSON field with the desired data:

php
$json_data = ['total' => 22, 'time' => 5];
$table->where(...)->update(['column->data' => $table->getConnection()->raw('JSON_SET(column->data, "$.total", ?, "$.time", ?)', [$json_data['total'], $json_data['time']])]);


In this code snippet, we are using the `JSON_SET` function provided by MySQL to update the JSON field with the new data. The `getConnection()->raw()` method allows us to execute raw SQL queries within Laravel's Eloquent ORM.

Make sure to replace `...` with the appropriate conditions for updating the record in the database.

Rate this post

3 of 5 based on 7655 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us