How to Set a Value to NULL when using Zend_Db

2019-02-17 14:06发布

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?

4条回答
地球回转人心会变
2楼-- · 2019-02-17 14:17

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

查看更多
欢心
3楼-- · 2019-02-17 14:20

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;
    }
}
查看更多
叛逆
4楼-- · 2019-02-17 14:38

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 ;-)

查看更多
我命由我不由天
5楼-- · 2019-02-17 14:40

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);
查看更多
登录 后发表回答