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

Codeigniter3动态传递分类ID复用产品查询函数及参数错误解决

CodeIgniter 3:动态传递分类ID复用查询函数并解决参数错误问题

问题分析

当前修改后出现两个核心问题:

  1. 控制器中$id变量未定义,导致报错
  2. 模型函数强制要求传参,不传则触发ArgumentCountError
  3. 隐藏问题:原缓存Key未包含分类ID,不同分类的查询会共用缓存,导致数据混乱

解决方案

1. 修正模型函数:设置参数默认值+修复缓存Key

给参数设置默认值兼容无参调用,同时修改缓存Key加入分类ID,确保不同分类缓存独立:

// 获取指定分类的产品
public function get_products_by_category_id($id = 1)
{
    $lc_key = get_location_cache_key($this);
    // 缓存Key加入分类ID,避免不同分类缓存冲突
    $key = "special_offers_lang_{$this->selected_lang->id}_cat_{$id}";
    $result_cache = get_cached_data($this, $key, "pr");
    
    if (!empty($result_cache) && !empty($result_cache[$lc_key])) {
        return $result_cache[$lc_key];
    }

    $result_cache = array();
    $this->build_query();
    $this->db->where('products.category_id', $id);
    $this->db->order_by('products.created_at', 'DESC')->limit(20);
    $result = $this->db->get('products')->result();

    $result_cache[$lc_key] = $result;
    set_cache_data($this, $key, $result_cache, "pr");
    return $result;
}

关键修改点:

  • 给$id设置默认值1,兼容不传参数的场景
  • 缓存Key追加_cat_{$id},确保不同分类的缓存互不干扰

2. 修正控制器:传递合法的分类ID

根据业务场景给$id赋值,解决未定义问题,示例如下:

场景1:从URL路由获取单个分类ID

// 假设路由规则为 /products/category/{id},默认分类ID为1
$id = $this->uri->segment(3, 1);
$data["category_products"] = $this->product_model->get_products_by_category_id($id);

场景2:一次性获取多个分类产品(满足视图$category_products[1]、$category_products[2]的需求)

// 定义需要获取的分类ID列表
$target_category_ids = [1, 2, 3];
$data["category_products"] = [];

foreach ($target_category_ids as $cat_id) {
    $data["category_products"][$cat_id] = $this->product_model->get_products_by_category_id($cat_id);
}

3. 视图调用规范

遵循MVC架构,避免在视图中直接调用模型,改用控制器传递的数据:

单个分类产品渲染

<?php foreach ($category_products as $product): ?>
    <!-- 产品内容渲染逻辑 -->
    <div class="product-item"><?= $product->name ?></div>
<?php endforeach ?>

多个分类产品渲染

<!-- 渲染分类1的产品 -->
<h3>分类1产品</h3>
<?php foreach ($category_products[1] as $product): ?>
    <div class="product-item"><?= $product->name ?></div>
<?php endforeach ?>

<!-- 渲染分类2的产品 -->
<h3>分类2产品</h3>
<?php foreach ($category_products[2] as $product): ?>
    <div class="product-item"><?= $product->name ?></div>
<?php endforeach ?>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 11:31:00