【问题标题】:PHP / Laravel Firebase Realtime Database updating a specific fieldPHP / Laravel Firebase 实时数据库更新特定字段
【发布时间】:2019-03-29 14:59:17
【问题描述】:

我正在尝试使用 kreait/firebase-php 包更新 firebase 实时数据库。

这是我的树:

我需要更新具有is_read 值为false/detail/pesan/1/<unique ID> 的孩子并将其更新为true

这是我的部分代码:

        $database = $firebase->getDatabase();

        $id_pesan=1;

        /*
            Update Firebase is_read 
        */
        $update = ['/is_read'  => "true"];

        $updatePesan_1 = $database
        ->getReference('chat/detail/'. $id_pesan)
        ->orderByChild('is_read')
        ->equalTo('false')
        ->update($update);

但我收到此错误:

Call to undefined method Kreait\Firebase\Database\Query::update()

当我先更改它以获取值然后更新/设置它:

$updatePesan_1 = $database
        ->getReference('chat/detail/'. $id_pesan)
        ->orderByChild('is_read')
        ->equalTo('false')
        ->getValue()
        ->set($update);

我收到此错误:

{"status":"error","error":400,"message":"索引未定义,添加\".indexOn\":\"is_read\",用于路径\"/chat/detail/ 1\",遵守规则"}

我要做的是首先过滤/查询数据库以查找具有 is_read = false 的特定树的子节点,并将值从“false”更新为“true”。

是否可以查询firebase数据库然后更新它?

如果是,我该如何修复我的代码来实现这一点?

【问题讨论】:

标签: php laravel firebase firebase-realtime-database


【解决方案1】:

这是我的解决方案

好的,经过多次研究和反复试验。

我做了几件事:

  1. 更改新规则以启用在 firebase 数据库上编辑特定字段
  2. 更改 PHP 代码,因为我无法进行过滤/查询然后更新。所以我不得不在没有过滤/查询的情况下进行,然后更新数据

1. Firebase 数据库规则的更改

我把规则改成这样:

{
"rules": {
".read": true,
".write": true,
"chat": {
  "detail": {
    "$id_pesan" :{
      ".indexOn": ["is_read"]
     }
   }
  }
 }
}

一些简短的解释: 数据存储在chat/detail/// 因为我需要能够更改里面的内容,所以我添加了 ".indexOn" : ["is_read"] 我更改了规则并将索引放在 chat/detail/ 中。

2。更改 PHP 代码

一开始我想做的是这样的:

  1. 初始化 Firebase
  2. 设置引用
  3. 在查询字段时执行更新调用(在 1 次调用中)

但似乎该软件包不支持我想做的事情。因此,我必须先查询该字段并获取唯一 ID 值。然后我把它做成了一个关联数组,然后用它来更新数据库

这是新代码

 //initialize
 $database = $firebase->getDatabase();

 //get value of all the unique ID
 $getValue = $database
        ->getReference('chat/detail/'. $id_pesan)
        ->orderByChild('is_read')
        ->equalTo('false')
        ->getValue();

//initialize Array
$update = [];

//make the array necessary to update the firebase database
/* 
     What the Array should looks like 
     <Unique ID>/<variable I wanted to change> => "<new Value>"
     Example :
     "-IUAYS678/is_read" => "true"
     "-JVHBY817/is_read" => "true"
*/
foreach($updatePesan_1 as $k => $v)
{
    $update[$k. "/is_read"]="true";
}

//Update the Firebase Database
$updatePesan_1_process=$database->getReference('chat/detail/'. $id_pesan)
->update($update);

希望对你有帮助

【讨论】:

    猜你喜欢
    • 2022-06-10
    • 1970-01-01
    • 2018-09-14
    • 1970-01-01
    • 2017-11-30
    • 1970-01-01
    • 2021-03-15
    • 2019-03-14
    • 1970-01-01
    相关资源
    最近更新 更多