Skip to main content

Drupal 8: DB query, how to use NOT EXISTS or NULL condition

    $database = \Drupal::database();
    $query = $database->select('sound_raw_data', 's');
    $query->fields('s');
    $query->isNull('field_nullable');
    $query->range(0,1000);
    $soundDataResult = $query->execute()->fetchAll();
    if ($soundDataResult) {
        foreach ($soundDataResult as $key => $row) {
            $query = $database->update('sound_raw_data')
                ->fields(['a2calc' => lMinEqA($row->a2)])
                ->where(
                    'id = :row_id',
                    ['row_id' => $row->id]
                )
                ->execute();
        }
    }

This is a snippet where i find all the records from a custom database table that the field field_nullable has null values. I use then, another query in order to update all the records with null values of the field_nullable based on the value of another field.

This query returns all the fields for each row. If you want to select only some specific fields then you have to do this:

    $query = $database->select('sound_raw_data', 's');
    $query->fields('s',['id','a2calc','created']);
    $query->condition('created', array($fromTimeRaw, $toTimeRaw), 'BETWEEN');
    $soundDataResult = $query->execute()->fetchAll();

Here i select the fields [id,a2calc,created] plus you can see how to use the between condition param in order to get the date range from a unit timestamp field.

Here are some other possible ways to get the "empty" fields.

$query->notExists($field);
$query->isNull($field);
$query->isNotNull($field);
$query->exists($field);

 

database