繁体   English   中英

如何使用 Laravel 框架更新 MySQL 中的 json 数据?

[英]How can I update json data in MySQL with Laravel framework?

我想用 Laravel 创建一个票务系统。 我将聊天数据存储在 json 数据类型中。 当用户想要发送她/他的票时,我会获取她/他的数据并将其存储在以下代码中:

$messages = array([
    'message_title' => post('message_title'),
    'message_body' => post('message_body'),
    'type' => 'q',
    'created_at' => date('Y/m/d H:i:s'),
]);

$messagesToJson = json_encode($messages);
$query = DB::table('test')->insert([
    'level_id' => post('message_level'),
    'status' => 0,
    'ticket_id' => post('user_id') . time(),
    'user_id' => post('user_id'),
    'backend_user_id' => '',
    'messages' => $messagesToJson,
]);

这些数据存储在 MySQL 中:

[
    {"message_title":"This is title","message_body":"Some text ... .","type":"q","created_at":"2020\/02\/29 20:42:26"}
]

但我的问题是:当用户想在这张票中提出一个新问题时,我如何在这个数组中插入一个新对象,如下所示:

[
    {"message_title":"This is title","message_body":"Some text ... .","type":"q","created_at":"2020\/02\/29 20:42:26"},
    {"message_title":"Question 2","message_body":"Some text in question 2 ... .","type":"q","created_at":"2020\/02\/29 21:42:26"}
]

我的更新代码是:

$messages = array(
    'message_body' => post('sendText'),
    'type' => 'q',
    'created_at' => date('Y/m/d H:i:s'),
);

$messagesToJson = json_encode($messages);
$updateQuery = DB::update("UPDATE synon_subsystem_ticketing
                  SET messages = JSON_SET(messages, '$[$countMessages]', '$messagesToJson') WHERE id = '$id'");

您有 2 个选择:

  1. 获取当前值,附加您的消息并更新:

     $tiket = DB::table('synon_subsystem_ticketing')->find($id); $messages = json_decode($ticket->messages) ?? []; //json_decode is not necessary if you're using attribute casting on your model $messages[] = array( 'message_body' => post('sendText'), 'type' => 'q', 'created_at' => date('Y/m/d H:i:s'), ); $messages = json_encode($messages); //json_encode is not necessary if you're using attribute casting on your model DB::table('synon_subsystem_ticketing') ->where('id', $id) ->update(['messages' => $messages]);

    注意:在迁移更新 json 列的json 列上检查 Laravel 文档

  2. 在原始查询上使用 MySql JSON_ARRAY_APPEND函数。

MySQL 支持 json 列。 您可以在 laravel 中创建和更新 json 列,如下所示。

$table->json('tickets_user_info'); // in your migration create json column.

//Update it as shown below.
$affected = DB::table('users')
          ->where('id', 1)
          ->update(['tickets_user_info' => 'what_ever_you_want_to_save_here']);

您可以创建包含旧数据的新数组并使用所有数据更新您的 json 列。

阅读 laravel 的查询 Json 列更新 JSON 列

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM