Update Entities


  • To modify existing documents:

    • Retrieve documents from the database using load or by a query.
      The entities loaded from the documents are added to the internal entities map that the session manages.

    • Edit the properties you wish to change.
      The session will track all changes made to the loaded entities.

    • Save to apply the changes.
      Once saveChanges() returns it is guaranteed that the data is persisted in the database.

  • In this page:


Load a document & update

  • In this example we load a company document and update its PostalCode property.

$session = $store->openSession();
try {
    // Load a company document
    // The entity loaded from the document will be added to the Session's entities map
    /** @var Company $company */
    $company = $session->load(Company::class, "companies/1-A");

    // Update the company's PostalCode
    $address = $company->getAddress();
    $address->setPostalCode("TheNewPostalCode");
    $company->setAddress($address);

    // Apply changes
    $session->saveChanges();
} finally {
    $session->close();
}

Query for documents & update

  • In this example we query for company documents whose PostalCode property is 12345,
    and modify this property for the matching documents.

$session = $store->openSession();
try {
    // Query: find companies with the specified PostalCode
    // The entities loaded from the matching documents will be added to the Session's entities map
    $query = $session->query(Company::class)
        ->whereEquals("address.postal_code", "12345");

    $matchingCompanies = $query->toList();

    // Update the PostalCode for the resulting company documents
    for ($i = 0; $i < count($matchingCompanies); $i++) {
        $address = $matchingCompanies[$i]->getAddress();
        $address->setPostalCode("TheNewPostalCode");
        $matchingCompanies[$i]->setAddress($address);
    }

    // Apply changes
    $session->saveChanges();
} finally {
    $session->close();
}