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

CodeIgniter API按ID获取指定城市数据失败,返回全量数据的问题

解决CodeIgniter REST API返回全部城市而非指定ID数据的问题

咱们一步步排查并解决这个问题:

1. 先修正请求URL的错误

你的两个请求URL都存在问题,这是导致参数无法正确传递的核心原因之一:

  • 方式1:URL里的参数缺少名称,应该是?id=1而不是?=1,正确的URL格式是:

    http://localhost:81/weatherapi/index.php/Cities/index?id=1
    

    这样$this->get('id')才能正确抓取到id参数的值。

  • 方式2:这种分段式URL(/index/1)需要控制器方法支持接收URL分段参数,但当前你的index_get方法没有定义参数,所以无法获取到这个1。

2. 调整控制器方法,兼容两种传参方式

如果你想同时支持GET参数和URL分段两种传参形式,可以修改控制器的index_get方法,让它能处理两种情况:

<?php defined('BASEPATH') OR exit('No direct script access allowed'); 
require_once APPPATH . '/libraries/REST_Controller.php'; 

class Cities extends REST_Controller { 
    public function __construct() { 
        parent::__construct(); 
        $this->load->model('cities_model'); 
    } 

    // 增加$id参数并设置默认值为null
    public function index_get($id = null) { 
        // 优先使用URL分段的id,如果没有则取GET参数里的id
        $city_id = $id ?? $this->get('id');
        $cities = $this->cities_model->get($city_id); 

        if (!is_null($cities)) { 
            $this->response(array('response' => $cities), 200); 
        } else { 
            $this->response(array('error' => 'No hay ciudades en la base de datos...'), 404); 
        } 
    } 
}

修改完成后,两种请求方式都能正常工作:

  • 方式1(GET参数):http://localhost:81/weatherapi/index.php/Cities/index?id=1
  • 方式2(URL分段):http://localhost:81/weatherapi/index.php/Cities/index/1

3. 确认模型逻辑的正确性

你的模型代码逻辑是没问题的:当传入有效的$id时,会执行带WHERE id = $id的查询,返回单条城市数据;当$id为null时,返回全部城市。只要控制器能正确传递$id参数,模型就能正常输出结果。

最后测试验证

修改完成后,用Postman重新发起请求:

  • 使用修正后的方式1 URL,应该返回ID为1的城市数据;
  • 使用方式2 URL,同样应该返回ID为1的城市数据;
  • 如果不传ID参数(比如http://localhost:81/weatherapi/index.php/Cities/index),会返回全部城市数据,这符合预期逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:37:58