2012-06-16 65 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更新了我的答案 –

相关问题