我有一张这样的表。
[id] [name] [age]
1 foo 20
2 bar NULL
如果我需要在年龄字段为 NULL 时返回所有行,我会执行以下操作,它工作正常。
$this->db->from('person')->where('age', null);
问题是我需要做相反的事情,我的意思是,当年龄字段不是空值时返回所有行。
在SQL中,我做这样的事情
SELECT * FROM person WHERE age is not null
如何使用代码点火器活动记录来执行此操作?
任何帮助表示赞赏。
您可以使用:
$this->db->from('person')->where('age is not null');
如果您想知道这是如何发生的,请参阅system/database/DB_active_rec.php
protected function _where($key, $value = NULL, $type = 'AND ', $escape = NULL)
{
...
if (is_null($v) && ! $this->_has_operator($k))
{
// value appears not to have been set, assign the test to IS NULL
$k .= ' IS NULL';
}
...
}
和system/database/DB_driver.php
/**
* Tests whether the string has an SQL operator
*
* @access private
* @param string
* @return bool
*/
function _has_operator($str)
{
$str = trim($str);
if ( ! preg_match("/(s|<|>|!|=|is null|is not null)/i", $str))
{
return FALSE;
}
return TRUE;
}
因此,您可以只将第一个参数传递给where()
方法,如果此方法的第一个运算符具有子字符串is not null
则它保持不变。
阅读更多 - 代码点火器论坛
必须这样做:
$this->db->from('person')->where('age IS NOT NULL', null);