【问题标题】:CodeIgniter active record limit with joinCodeIgniter 活动记录限制与连接
【发布时间】:2015-11-02 00:20:38
【问题描述】:

我的模型中有以下功能:

function getLocations($limit = null, $offset = null){
    $this->db->select('*');
    $this->db->from('location');
    $this->db->join('process', 'process.process_id=location.process_id');
    $this->db->join('line', 'line.line_id=process.line_id');
    $this->db->limit($limit, $offset);
    $this->db->order_by('location_id', 'asc');
    return $this->db->get()->result();
}

然后使用:$this->the_model->getLocations() 执行,产生以下查询:

SELECT *
FROM "location"
JOIN "process" ON "process"."process_id"="location"."process_id"
JOIN "line" ON "line"."line_id"="process"."line_id"
ORDER BY "location_id" asc LIMIT 0

注意LIMIT 0,当我执行$this->db->order_by('item_id', 'asc')->get('item', $limit, $offset)->result() 时不会发生这种情况。没有LIMIT 0 甚至限制,偏移量是null。那么,如何解决这个问题呢?当限制为空时,我已经添加了if 条件。

【问题讨论】:

  • 你好,null不代表=0,你可以试试getLocations($limit = 0,$offset = 0)

标签: php sql codeigniter


【解决方案1】:

0 是一个值。这并不意味着0NULL。而NULL 则毫无价值。

对于你的情况,

function getLocations($limit = 1, $offset = 0){
                               ^            ^ 
    $this->db->select('*');
    $this->db->from('location');
    $this->db->join('process', 'process.process_id=location.process_id');
    $this->db->join('line', 'line.line_id=process.line_id');
    $this->db->limit($limit, $offset);
    $this->db->order_by('location_id', 'asc');
    return $this->db->get()->result();
}

limit 至少设置为1 并将偏移量设置为0 作为默认值。

【讨论】:

    【解决方案2】:

    试试这个

    function getLocations($limit , $offset){
        $query = $this->db->query(
            "SELECT *
            FROM location
            JOIN process ON process.process_id=location.process_id
            JOIN line ON line.line_id=process.line_id
            ORDER BY location_id asc LIMIT $limit, $offset");
        $result = $query->result_array();
        return $result;
    }
    

    不要设置$limit = NULL。这将解决问题

    【讨论】:

    • 谢谢,但有时我需要限制和偏移,有时不需要。
    • 然后使用另一个函数。如果您使用函数,它不会对您的项目性能产生任何影响
    【解决方案3】:

    感谢那些回答我问题的人。

    我通过将代码调整为:

    function getLocations($limit = null, $offset = null){
        $this->db->select('*');
        $this->db->join('process', 'process.process_id=location.process_id');
        $this->db->join('line', 'line.line_id=process.line_id');
        $this->db->order_by('location_id', 'asc');
        return $this->db->get('location', $limit, $offset)->result();
    }
    

    这样,即使$limitnull,生成的查询中也没有LIMIT 0

    非常感谢。

    【讨论】:

      猜你喜欢
      • 2014-06-25
      • 1970-01-01
      • 2014-06-22
      • 2012-11-23
      • 2011-07-08
      • 1970-01-01
      • 2013-07-30
      • 1970-01-01
      相关资源
      最近更新 更多