You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在CodeIgniter中批量删除指定记录及排除指定记录

Hey there! Let's work through your two deletion requirements using your current CodeIgniter controller and model code. I'll break down each scenario and show you the adjusted code to make it work.

1. 批量删除指定ID的记录(ID: 4、6、8、11、12)

Your current model only handles deleting a single campus_id, but we need to modify it to accept an array of IDs for bulk deletion. Here's how to adjust your code:

Updated Controller Function

Your existing controller already splits the $value into an array of IDs, so we just need to keep that part and ensure we're passing the array correctly:

public function delete_data($id, $value) {
    $oris = explode("_", $value);
    $oris = array_filter($oris); // Remove any empty values from the split
    $this->o->delete_data($oris); // Pass the array of IDs to the model
}

Updated Model Function

We'll use CodeIgniter's where_in() method to target multiple IDs at once:

public function delete_data($ids) {
    // Handle both single ID and bulk ID cases for flexibility
    if (is_array($ids)) {
        $this->db->where_in('campus_id', $ids);
    } else {
        $this->db->where('campus_id', $ids);
    }
    $this->db->delete('sections');
}

This way, if you pass a single ID or an array of IDs (like 4,6,8,11,12), the model will handle it correctly. The query will delete all matching records in one go.

2. 删除记录时排除指定ID(排除ID: 3、5、6、7)

To delete all records except the specified IDs, we'll use CodeIgniter's where_not_in() method. It's best to create a separate model method for this to keep logic clear, or add a parameter to distinguish deletion types. Let's go with a dedicated method:

New Model Method for Exclusion Deletion

public function delete_data_except($exclude_ids) {
    // Ensure we're working with an array of IDs to exclude
    if (is_array($exclude_ids)) {
        $this->db->where_not_in('campus_id', $exclude_ids);
    }
    $this->db->delete('sections');
}

Controller Usage (Example)

If you need to trigger this from a controller, here's a sample function:

public function delete_data_except() {
    $exclude_ids = [3,5,6,7]; // The IDs you want to keep in the table
    $this->o->delete_data_except($exclude_ids);
}

This will delete every record in the sections table where campus_id is not in the exclude_ids array.

A quick best practice note: Always validate and sanitize input IDs before passing them to your model. CodeIgniter's query builder methods handle automatic escaping, but it's still smart to ensure inputs are valid (e.g., only numeric IDs) to avoid unexpected issues.

内容的提问来源于stack exchange,提问作者John David

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 03:32:50