2012-06-16 62 views
2

我正在和Zend一起工作,我需要檢查數據庫中的一行是否已經存在(一個簡單的解決方案來擺脫我得到的重複鍵錯誤)。我試了好東西,但似乎沒有任何工作...(例如Zend_Validate_Db_NoRecordExists法)這是檢查db_row是否存在的有效方法嗎?

所以我寫的代碼下面,我想知道,這是做一個有效的辦法,還是我應該做不同的事情:

在模型:

$where = $condition = array(
     'user_id = ' . $user_id, 
     'page_id = ' . $page_id 
     ); 

     $check = $this->fetchRow($where); 

     if(count($check) > 0) { 

      return null; 

     }else{ 
       // Here I create a new row, fill it with data, save and return it. 
     } 

然後在我的觀點:

if($this->result != null) { /* do stuff */ }else{ /* do other stuff */ } 

它的工作,但它確實需要更多的時間(廢話,因爲額外的查詢)和我有點不確定我是否應該用這根棍子..

任何建議都是歡迎的。

回答

2

假設你有你的編碼功能,在您的控制器

$row = $this->fetchRow($where); //If no row is found then $row is null . 

    if(!$row) 
    { 
    $row = $dbTb->createNew($insert); //$insert an associative array where it keys map cols of table 
    $row->save(); 
    $this->view->row_not_found = true; 
    } 

    return $row; 

在你看來,你可以做到這一點

if($this->row_not_found) 
{ 
}else { 

} 
+0

啊!如果沒有找到行,我忘記了fetch方法自動返回null。我用來插入新數據的方法是通過'$ row = $ this-> createRow'然後'if($ row){$ row-> user_id = $ user_id .. etc.'謝謝你! – Cooleronie

+0

但是!等待..現在$行總是返回一個值..我需要它返回NULL,如果行**已存在,因爲這是我需要知道在我看來!我添加了一個'} else {return null',就像一個魅力。 – Cooleronie

+0

@Cooleronie更新了我的答案 –

相關問題