Current Location: Home> Latest Articles> Detailed Guide to Data Deletion Methods in ThinkPHP

Detailed Guide to Data Deletion Methods in ThinkPHP

gitbox 2025-06-30

Detailed Explanation of ThinkPHP Data Deletion Method

ThinkPHP is a representative open-source PHP framework from China, widely used in web development. Based on the MVC design pattern, it is known for its efficiency, ease of use, and security.

In ThinkPHP, deleting data is one of the common operations. With the delete method, we can easily remove records from the database. Below, we’ll dive into the usage of this method and its related parameters.

Syntax of the delete Method

The syntax of the delete method is as follows:

public function delete($ids = null, $options = [], $force = false)

This method accepts three parameters:

Parameter 1: $ids

$ids represents the IDs of the records to be deleted. It can be a single ID or an array of IDs. If set to null, all records will be deleted.

Parameter 2: $options

$options is used to define deletion conditions and other configuration details. It can be a string, an array, or an object.

If it’s a string, the content of $options should be the WHERE clause in an SQL query. For example:

$options = 'id > 10';

If it’s an array, $options can include the following fields:

  • where: Query condition, similar in format to a string.
  • table: The name of the table to operate on.
  • limit: The maximum number of records to delete.

For example:

$options = [
    'where' => 'id > 10',
    'table' => 'my_table',
    'limit' => 10
];

If it’s an object, it should implement the Arrayable interface.

Parameter 3: $force

$force is a boolean parameter. If set to true, it forces the deletion. If false, it checks for foreign key constraints, and the deletion will not occur if such constraints exist.

Example of a Deletion Operation

Suppose we have a table named users. Here’s an example of using the delete method:

We can delete records with IDs greater than 5 using the following code:

$User = M('User');
$result = $User->delete('5,6,7');

In this example, "5,6,7" are the record IDs to be deleted. Both single and multiple IDs in an array are supported. To delete all records, you can set $ids to null, like this:

$result = $User->delete(null);

If you want to delete records based on other conditions, you can set them through the $options parameter. For example:

$options = [
    'where' => 'status = 0',
    'table' => 'users',
    'limit' => 10
];
$result = $User->delete(null, $options);

In this case, the $options array specifies the deletion condition, table name, and record limit.

Conclusion

This article introduced the basic usage of the delete method in ThinkPHP. With this method, developers can efficiently perform data deletion operations while using flexible configurations to meet different requirements.