Delete.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <?php
  2. namespace Drupal\Core\Database\Query;
  3. use Drupal\Core\Database\Database;
  4. use Drupal\Core\Database\Connection;
  5. /**
  6. * General class for an abstracted DELETE operation.
  7. *
  8. * @ingroup database
  9. */
  10. class Delete extends Query implements ConditionInterface {
  11. use QueryConditionTrait;
  12. /**
  13. * The table from which to delete.
  14. *
  15. * @var string
  16. */
  17. protected $table;
  18. /**
  19. * Constructs a Delete object.
  20. *
  21. * @param \Drupal\Core\Database\Connection $connection
  22. * A Connection object.
  23. * @param string $table
  24. * Name of the table to associate with this query.
  25. * @param array $options
  26. * Array of database options.
  27. */
  28. public function __construct(Connection $connection, $table, array $options = []) {
  29. $options['return'] = Database::RETURN_AFFECTED;
  30. parent::__construct($connection, $options);
  31. $this->table = $table;
  32. $this->condition = new Condition('AND');
  33. }
  34. /**
  35. * Executes the DELETE query.
  36. *
  37. * @return int
  38. * The number of rows affected by the delete query.
  39. */
  40. public function execute() {
  41. $values = [];
  42. if (count($this->condition)) {
  43. $this->condition->compile($this->connection, $this);
  44. $values = $this->condition->arguments();
  45. }
  46. return $this->connection->query((string) $this, $values, $this->queryOptions);
  47. }
  48. /**
  49. * Implements PHP magic __toString method to convert the query to a string.
  50. *
  51. * @return string
  52. * The prepared statement.
  53. */
  54. public function __toString() {
  55. // Create a sanitized comment string to prepend to the query.
  56. $comments = $this->connection->makeComment($this->comments);
  57. $query = $comments . 'DELETE FROM {' . $this->connection->escapeTable($this->table) . '} ';
  58. if (count($this->condition)) {
  59. $this->condition->compile($this->connection, $this);
  60. $query .= "\nWHERE " . $this->condition;
  61. }
  62. return $query;
  63. }
  64. }