Home  >  Article  >  PHP Framework  >  How to delete multiple data in ThinkPHP 5

How to delete multiple data in ThinkPHP 5

PHPz
PHPzOriginal
2023-04-11 10:42:46418browse

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.

Preparation

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 = &#39;id&#39;;
    protected $table = &#39;user&#39;;
}

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 &#39;&#39;,
  `password` varchar(50) NOT NULL DEFAULT &#39;&#39;,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

Delete multiple data

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.

Test to delete multiple 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.

Conclusion

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn