How to Set a Value to NULL when using Zend_Db

回眸只為那壹抹淺笑 提交于 2019-12-19 07:19:42

问题


When performing UPDATE and INSERT queries using Zend_Db, I frequently need to set values equal to NULL (not ''). However, the default behavior of Zend_Db::insert() and Zend_Db::update() seems to be that values that are empty are translated into empty strings ('') and put into the database as such.

Does anyone know of way to actually force a NULL value to go into fields if the value is empty in php?


回答1:


Try setting the affected fields to: new Zend_Db_Expr('NULL')




回答2:


I've always just been able to do this using PHP's null:

$toUpdate = array('nullValue' => null, 'otherValue' => 'something');
Zend_Db::update($table, $toUpdate, $where);



回答3:


As Johrn I was able to do this with PHP's null value:

$value = null;
$what = array($columnName => $value);
$where = $this->_dbTableName->getAdapter()->quoteInto('Id = ?', $dbRecord->Id);
$this->_dbTableName->update($what, $where);

but encountered situations where the database itself had the column set to NOT NULL and in such cases the value was indeed converted to either empty string or in case of FLOATs to 0.00. I guess INT column would end up as 0 ;-)




回答4:


While using Zend 2.4.7 for those who may be visiting this issue, I was able to use this with William Lannen's answer providing some inspiration. Assuming getTable() returns a Zend\Db\TableGateway object:

public function fetch()
{
    $data['column_name1 = ?'] = 'column_value';
    $data[] = new \Zend\Db\Sql\Predicate\IsNull('column_name2');
    $resultSet = $this->getTable()->select($data);
    if (0 === count($resultSet) {
        return 'SomeExpectationOrException';
    } else {
        return $resultSet;
    }
}


来源:https://stackoverflow.com/questions/1173690/how-to-set-a-value-to-null-when-using-zend-db

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!