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

如何在CodeIgniter代码中使用order_by RAND()随机加载数据?

解决CodeIgniter数据随机加载无效的问题

问题原因

你添加RAND()后无效,核心原因是自定义的basic->get_data()方法没有接收并处理排序参数,或是你没有正确将排序规则传递给这个方法。

具体解决方案

1. 修改get_data()方法以支持排序

打开你的basic模型文件,找到get_data()方法,添加排序逻辑:

public function get_data($table, $where = [], $select = [], $join = [], $order_by = '')
{
    // 处理字段选择
    if (!empty($select)) {
        $this->db->select(implode(',', $select));
    }

    // 处理关联查询
    foreach ($join as $table_name => $join_rule) {
        list($on_clause, $join_type) = explode(',', $join_rule);
        $this->db->join($table_name, $on_clause, $join_type);
    }

    // 处理WHERE条件
    if (isset($where['where']) && !empty($where['where'])) {
        $this->db->where($where['where']);
    }

    // 新增:处理随机排序
    if (!empty($order_by)) {
        $this->db->order_by($order_by);
    }

    return $this->db->get($table)->result();
}

2. 调用时传入随机排序参数

修改业务代码,添加$order_by参数并传入'RAND()':

$select = ['account_access_token','account_config_id'];       
$where = ['where'=>['enable_marketing' => '1', 'account_config_id.id!=' => $account_table_id]]; 
$join = ['account_user_info'=>'account_config_id.account_user_info_id=account_user_info.id,left'];       
// 传递随机排序规则
$order_by = 'RAND()';
$pages_info = $this->basic->get_data('account_config_id',$where,$select,$join,$order_by);

3. 排查缓存问题(若上述方法无效)

如果仍返回相同结果,检查是否开启了缓存:

  • 关闭查询缓存:在查询前执行$this->db->cache_off();
  • 禁用页面缓存:若控制器开启了输出缓存(如$this->output->cache(5);),注释该行或设置缓存时间为0。

补充说明

如果你的get_data()原本支持通过$where数组传递排序,也可直接修改$where:

$where = [
    'where'=>['enable_marketing' => '1', 'account_config_id.id!=' => $account_table_id],
    'order_by' => 'RAND()'
];

同时确保模型会读取$where['order_by']并执行排序。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 23:25:10