Firebase PHP: Updating also deletes the other children

Viewed 1405

I am using the Firebase PHP Admin SDK: https://firebase-php.readthedocs.io/en/stable/realtime-database.html#update-specific-fields

Here is the example it gives to update specific fields:

$uid = 'some-user-id';
$postData = [
    'title' => 'My awesome post title',
    'body' => 'This text should be longer',
];

// Create a key for a new post
$newPostKey = $db->getReference('posts')->push()->getKey();

$updates = [
    'posts/'.$newPostKey => $postData,
    'user-posts/'.$uid.'/'.$newPostKey => $postData,
];

$db->getReference() // this is the root reference
   ->update($updates);

From that, I created a users class and in that I have an update function. Like so:

public function update() {

    $data = array('users' => array('1' => 'David'));
    $this->database->getReference()->update($data);

    return true;
}

In my database I have this structure:

enter image description here

Now if I run that function $users->update();

It removes the other child and only leaves David. Like so:

enter image description here

How can I update only a specific value of a specified key without it overriding the other data?

2 Answers

There's nothing specific to PHP here. That's the way Realtime Database update operations work. If you want a minimal update, you have to target the deepest key that you want to update. In your case, since you're storing an array type object, the keys are the number indexes of the array items you've written. If you want to modify one of them, you need to build a reference that includes the child number you want update. In that case, none of the sibling values will be touched.

Try this instead:

$this->database->getReference('users')->update(array('1' => 'David'));

Notice here that the update is rooted at "users", and you're updating just the immediate child "1" of that.

The example on docs is a little bit hard to grasp as a beginner. I have made it simpler for you to understand.

Once you get the newPostKey, prepare the url for child and run the code. It will only change the specific fields.

$ref = 'users/' . $newPostKey;  

$updates = [
    'title' => 'Updated title',
    'body' => 'Updated body text',
];

$set = $db->getReference($ref)->update($updates);
Related