Update Queries

Quickly update certain properties of certain entities without needing to load the entities first, using an update query.

If you load an entity, make changes to it, and want to save it again, you can just call the saveEntity method on your repository, and your changes will be saved. Sometimes though, you might have more complex requirements, like needing to update a property on multiple entities that match certain criteria, or you might want to update certain properties of an entity without loading the entity first. You can achieve this with an update query:

$query = QueryBuilder::create()
    ->update(Contact::class)
    ->set([
        'earnsCommission' => true, 
        'commissionRate' => 12.5
    ])
    ->where('department.name', '=', 'Sales')
    ->buildUpdateQuery();

The call to the update method in the above query is optional - if the repository you use to run the query already has an entity class name assigned, it will be used if you don't specify one in the query.

You can use other properties for the value, or in an expression if required:

$query = QueryBuilder::create()
    ->update(Contact::class)
    ->set([
        'higherRateEarner' => '%commissionRate% > 20'
    ])
    ->buildUpdateQuery();

In the above example, the percent symbols surrounding the word commissionRate tell Objectiphy that commissionRate is a property, and it will evaluate the expression to yield true or false, which is then used to populate the value of the higherRateEarner property.

Last updated