Query delete
Delete queries should always use the query builder object. They are initiated using the delete()
method as follows:
$query = $connection->delete('mytable', $options);
This creates a delete query object that removes records from the mytable
table. Note that curly braces are not required around the table name, as the query builder will handle this automatically.
The delete query object uses a fluent API. That means all methods (except execute()
) return the query object itself, allowing for method chaining. In many cases, this means the query object doesn’t need to be stored in a variable at all.
Delete queries are conceptually very simple and consist only of a WHERE clause. The full structure of WHERE clauses is explained in the section "Conditional Clauses" and will only be briefly touched on here.
A full delete query will take the following form:
$num_deleted = $connection->delete('mytable') ->condition('myfield', 5) ->execute();
The query above will delete all rows from the {mytable}
table where the column myfield
equals 5. This is equivalent to the following SQL query:
DELETE FROM {mytable} WHERE myfield=5;
The execute()
method returns the number of records that were deleted by the query.
Drupal’s online documentation is © 2000-2020 by the individual contributors and can be used in accordance with the Creative Commons License, Attribution-ShareAlike 2.0. PHP code is distributed under the GNU General Public License.