1. Use the delete method
In ThinkPHP, we can use the delete method to delete data. This method is very simple and only needs to be used in the model. Just use the delete method, for example:
$user = UserModel::get(1); $user->delete();
This way you can delete the user with ID 1. If your Model does not specify a primary key, you can use the following method:
$user = UserModel::get(['name' => 'thinkphp']); $user->delete();
In this way, you can delete the user named thinkphp.
2. Chain deletion
In ThinkPHP, we can also use chain deletion to delete data. This method is more commonly used, such as:
$user = UserModel::where('id', 1)->delete();
This method will delete the user data with ID 1 and return the number of deleted rows.
3. Soft deletion
In ThinkPHP, we can also use soft deletion to delete data. The so-called soft deletion means marking the data as deleted rather than actually deleting the data. This operation is useful in data recovery, data query, etc. We can use soft deletion in the model, for example:
class UserModel extends Model { use SoftDelete; protected $deleteTime = 'delete_time'; protected $defaultSoftDelete = 0; protected $autoWriteTimestamp = true; }
In this example, we use the Trait of SoftDelete and set the delete_time field to the deletion time. In this way, when we use the delete method or chain deletion method, the corresponding data will be marked as deleted instead of actually deleting the data.
4. Batch deletion
When developing projects, we sometimes need to delete data in batches. There are two methods:
1. Use SQL Statement
We can directly use SQL statements to delete data in batches, for example:
Db::table('user')->where('id', 'in', [1, 2, 3])->delete();
This method will delete user data with IDs 1, 2, and 3, and return the number of deleted rows.
2. Use the delete method of the model
We can also use the delete method of the model to delete data in batches, for example:
UserModel::destroy([1, 2, 3]);
This method will delete the IDs 1 and 2 , 3 user data, and returns the number of deleted rows.
The above is the detailed content of How to use the delete method in thinkphp. For more information, please follow other related articles on the PHP Chinese website!