2015-05-09 41 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; 
}