我正在使用 Zend,我需要检查数据库中是否已经存在一行(一个简单的解决方案来消除我遇到的重复键错误)。我尝试了几种方法,但似乎没有任何效果...(例如 Zend_Validate_Db_NoRecordExists 方法)
所以我编写了以下代码,我想知道这是否是一种有效的方法,或者我是否应该采取不同的做法:
在模型中:
$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 */ }
它确实有效,但似乎确实需要更多时间(呃,因为额外的查询),我有点不确定是否应该坚持这个..
欢迎任何建议:)
最佳答案
假设您已在 Controller 中编写了函数代码
$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 {
}
关于zend-framework - 这是检查 db_row 是否存在的有效方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11066451/