2015-05-09 20 views
1

我想限制CodeIgniter 3中的get_where函数的1行。出于某种原因它仍然返回所有行。需要使用限制1与get_where函数的帮助

有谁知道我该如何做这项工作?谢谢!

public function getNotes($applicant_id,$client_id,$last_note) 
{ 


    /*The notes are displayed by the applicant id that is passed by the $_GET variable from the Note controller 
    But just to be extra safe and make sure only the freelancer who is signed in can view the it will only show if the 
    session client id matched the client ID in the db */ 

    $limit = $last_note == true ? "LIMIT 1" : ""; 



    $this->db->order_by('client_notes_id', 'DESC'); 
    $qry = $this->db->get_where("client_notes", ["applicant_id" => $applicant_id, "client_id" => $client_id], $limit); 


    try { 
     $result = $qry->result(); 
     return $result; 


    } catch (Exception $e) { 
     // fb($e->getMessage()); 
    } 


} 
+0

如果没有ORDERBY子句,限制不会起作用,因此在限制之前将其添加,然后它将工作。您无法将ORDERBY与任何列名称一起使用。 –

回答

1

我认为这是你做错了什么:

$limit = $last_note == true ? "LIMIT 1" : "";

Query Builder Class指南中提到,$限制应integer

尝试,而不是$limit = 1$limit = "LIMIT 1"

+0

非常感谢!你在哪里是对的。我还了解到,你可以简单地做$ this-> db-> limit(1) – json2021

+0

@ json2021不客气 – Vladimir

0

根据您的要求,您可以使用三种方式。但最好的方法是

$this->db->from('client_notes'); 
$this->db->order_by('client_notes_id', 'DESC'); 
$this->db->where('applicant_id',$applicant_id); 
$this->db->where('client_id',$client_id); 
if($last_note) 
{ 
    $this->db->limit(1); 
} 
$qry = $this->db->get(); 


try { 
    $result = $qry->result(); 
    return $result; 


} catch (Exception $e) { 
    // fb($e->getMessage()); 
} 

他人

方式1.

$limit = $last_note == true ? 1 : NULL; 
$this->db->order_by('client_notes_id', 'DESC'); 
$qry = $this->db->get_where("client_notes", ["applicant_id" => $applicant_id, "client_id" => $client_id], $limit); 

方式2

if($last_note) 
{ 
    $this->db->limit(1); 
} 
$this->db->order_by('client_notes_id', 'DESC'); 
$qry = $this->db->get_where("client_notes", ["applicant_id" => $applicant_id, "client_id" => $client_id]); 

方式3

$this->db->order_by('client_notes_id', 'DESC'); 
$qry = $this->db->get_where("client_notes", ["applicant_id" => $applicant_id, "client_id" => $client_id]); 
try { 
    if($last_note) 
    { 
     $result=$qry->row();//remember it will produce the result differnt way 
    } 
    else 
    { 
     $result = $qry->result(); 
    } 
    return $result; 
}