I am trying to insert a new row based on conditions. The ->condition()
in $database->update()
works fine, in $database->insert()
they do not.
$database = \Drupal::database();
// Query our DB.
$queryDB = $database
->select('table_name', 'value3')
->fields('value3')
->condition('value1', $value1, "=")
->condition('value2', $value2, "=")
->execute()->fetchAll();
if (isset($queryDB[0])) {
// Check if table row exists and overwrite.
if ($queryDB[0]->value1 == $value1 && $queryDB[0]->value2 == $value2) {
$database
->update('table_name')
->fields([
'value3' => $value3,
])
->condition('value1', $value1, '=')
->condition('value2', $value2, '=')
->execute();
}
}
// Create table row.
else {
$database
->insert('table_name')
->fields([
'value1' => $value1,
'value2' => $value2,
'value3' => $value3,
])
// Without these conditions, I get a duplicate entry integrity restraint as value1 and/or value2 may already exist.
// With them I get Error: Call to undefined method Drupal\Core\Database\Driver\mysql\Insert::condition().
->condition('value1', $value1, '!=')
->condition('value2', $value2, '!=')
->execute();
}
Very similar questions: 1. EntityQuery condition "is not equal to..." 2. How do I add a condition to a query?
But I am having no luck. Is it different with an insert?
What I want is that if value1 AND value2 don't both match, create an entirely new table row with all three values.