【问题标题】:how to user jsonb_set on php while update json field on postgress如何在 php 上使用 jsonb_set 同时更新 postgres 中的 json 字段
【发布时间】:2021-03-31 18:38:49
【问题描述】:

我在 Postgres 上有表 my_tableid,name (varchar), properties (jsonb) 字段。

name 字段已经插入,现在我想在属性字段中添加一些数据。

<?php
         global $dbh;
        $queryUpdate = "UPDATE my_table set 
        properties=jsonb_set(coalesce(properties,'{}'),'{token_approval}','{$token}',true) where id=:id";
        $stmt = $dbh->prepare($queryUpdate);
        $stmt->bindValue(':id', $idPengajuanUtama);
        try {
            $stmt->execute();
        } catch (PDOException $e) {
            throw new RuntimeException($e->getMessage() . "\r\n Function " . __METHOD__);
            return false;
        }
        return true;
?>

当我运行代码时,我总是收到以下错误。

SQLSTATE[22P02]: Invalid text representation: 7 ERROR:  invalid input syntax for type json\nLINE 1: ..._set(coalesce(properties,'{}'),'{token_approval}','asdfadsna...\n

我该如何解决这个问题?

提前致谢。

【问题讨论】:

    标签: php json postgresql pdo sql-update


    【解决方案1】:

    你可以这样写查询:

    update my_table 
    set properties = jsonb_set(
        coalesce(properties, '{}'), 
        '{token_approval}', 
        to_jsonb(:token::text)
    )
    where id = :id
    

    请注意,这允许将令牌作为查询参数传递,而不是将其连接到查询字符串中。

    您可能会发现使用内置 jsonb 运算符更容易:

    update my_table 
    set properties = 
        coalesce(properties, '{}') 
            - 'token_approval' 
            || jsonb_build_object('token_approval', :token)
    where id = :id
    

    Demo on DB Fiddle

    【讨论】:

      猜你喜欢
      • 2016-12-17
      • 2014-02-02
      • 1970-01-01
      • 1970-01-01
      • 2020-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-11
      相关资源
      最近更新 更多