Home >PHP Framework >ThinkPHP >How to delete multiple data in ThinkPHP 5
Data manipulation in ThinkPHP 5 is very convenient. You can use the model's where
method to delete multiple data at one time. This article will introduce how to delete multiple data in ThinkPHP 5.
Before you start, please make sure you have installed ThinkPHP 5 and have a test database. This article takes deleting user information as an example. First, you need to create a User
model, as shown below:
<?php namespace app\index\model; use think\Model; class User extends Model { // 定义主键和表名 protected $pk = 'id'; protected $table = 'user'; }
User
The database table structure corresponding to the model is as follows:
CREATE TABLE `user` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `username` varchar(50) NOT NULL DEFAULT '', `password` varchar(50) NOT NULL DEFAULT '', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
Add a deleteUsers
method in the User
model. This method accepts an array parameter, and the array contains the user ID that needs to be deleted. . This method uses the where
method to delete multiple data, as shown below:
public function deleteUsers($ids) { $result = $this->where('id', 'in', $ids)->delete(); return $result; }
In the above code, the first parameter of the where
method is the field name, and the first parameter is the field name. The two parameters are operators, and the third parameter is the value that needs to be matched. The in
operator means to find the value of the id
field in the $ids
array. The data. Finally, call the delete
method to delete the matching data.
Write test code in the controller:
public function deleteUsers() { $ids = [1, 2, 3]; $userModel = new User(); $result = $userModel->deleteUsers($ids); if ($result) { return '删除成功'; } else { return '删除失败'; } }
In the above code, we call the deleteUsers
method to delete the ID 1 ,2,3 user data. Finally, the corresponding information is returned according to the deletion result.
It is very convenient to delete multiple data in ThinkPHP 5, just use the where
method. If you need to delete multiple data, please follow the method described in this article.
The above is the detailed content of How to delete multiple data in ThinkPHP 5. For more information, please follow other related articles on the PHP Chinese website!