I’m trying to create a dynamic query, the query logic conditions needed are: AND, and OR.
The main query will include two sub queries.
The ConditionInterface::condition documentation states that:
If called with 1 parameter, it should be a ConditionInterface that in itself forms a valid where clause. Use e.g. to build clauses with nested AND's and OR's.
I cannot find the example to build clauses with nested AND’s and OR’s so I’ve done some digging through the ConditionInterface API Reference (https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Database%21Query%21ConditionInterface.php/interface/ConditionInterface/8.6.x)
I found a function conditionGroupFactory (https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Database%21Query%21ConditionInterface.php/function/ConditionInterface%3A%3AconditionGroupFactory/8.6.x)
The conditionGroupFactory function appears to be what I need, however I cannot find any implementation examples.
Could someone please explain the implementation of this function.
$result = $connection->select('inventory', 'inv'); $result->fields('inv', ['part_number']); $result->condition('inv.visable', 1); $result->conditionGroupFactory('AND')->condition('inv.part_number', $queryOne, 'IN'); $result->conditionGroupFactory('OR')->condition('inv.part_number', $queryTwo, 'IN'); Note: $queryOne, $queryTwo; Are of type SelectInterface.
My Objective SQL Statement:
SELECT inv.part_number FROM inventory AS inv WHERE inv.visable = 1 AND (inv.part_number IN (SUBQUERY_1) OR inv.part_number IN (SUBQUERY_2));