Returns a new UpdateQuery object for the active database.

Returns a new UpdateQuery object for the active database.


Dinesh18’s picture

$query = \Drupal::database()->update('file_managed');
'uri' =>$uri,

jp.stacey’s picture

The previous comment is OK in module or other procedural code, but in object-oriented code (e.g. a custom block or other plugin, or a custom service) you should always use dependency injection:

use Drupal\Core\Database\Connection;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

class MyObject implements ContainerInjectionInterface {

  /* Dependency injection boilerplate begins. */
  protected $databaseConnection;

  public static function create(ContainerInterface $container) {
    return new static($container->get('database'));

  public function __construct(Connection $databaseConnection) {
    $this->databaseConnection = $databaseConnection;
  /* Boilerplate ends. */

  /* Your custom code. */
  public function someOtherCode(/* ... */) {
    $query = $this->databaseConnection->update(/* ... */);
    /* etc. */

If your class defines a plugin, you need to implement ContainerFactoryPluginInterface instead, which has a little bit more boilerplate but the same principle; example here.

dahousecat’s picture

I can use the dependency injection example in my own controller, but when my class extends ContentEntityBase (e.g. is a custom entity type) the __construct already has other variables being passed in.
Could you provide an example of how to use dependency injection to access the databaseConnection from within a class that extends ContentEntityBase?