简体   繁体   中英

CodeIgniter active record limit with join

I have the following function in my model:

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();
}

It is then executed using: $this->the_model->getLocations() resulting in the following 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 0

Notice LIMIT 0 , this does not happen when I execute $this->db->order_by('item_id', 'asc')->get('item', $limit, $offset)->result() . There is no LIMIT 0 even limit and offset is null . So, how to solve this? I already add if condition when limit is null.

0 is a value. This does not mean 0 is NULL . While NULL has no value at all.

For your case,

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();
}

Put the limit at least 1 and offset to be 0 for default values.

Try this

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;
}

Don't set $limit = NULL . this will fix the issue

thanks for those who response to my question.

I solved this by adjusting the code to:

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();
}

this way there is no LIMIT 0 in generated query even $limit is null .

thanks a lot.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM