2012-11-22 33 views
7

我有一张这样的表。使用CodeIgniter的NULL比较ActiveRecord

[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 

我怎么做到这一点使用CodeIgniter的ActiveRecord的?

任何帮助表示赞赏。

+0

希望这将有助于http://codeigniter.com/forums/viewthread/119444/P15 – sbaaaang

+0

你设置允许空DEFAULT NULL mysql的选项,你的数据库字段? – sbaaaang

+1

有用的论坛主题。 –

回答

11

您可以使用:

$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,它将保持不变。

要阅读更多 - CodeIgniter forum

+0

非常有用。谢谢。 –

-1

这必须是这样:

$this->db->from('person')->where('age IS NOT NULL', null); 
+0

我试过了,它不起作用。 ActiveRecord试图将该字段与NULL进行比较,但是NULL不会与任何东西进行比较,所以它会报告一个sql语法错误。 –

+0

尝试where('age IS NOT NULL',null) – mallix

+0

查看方法签名'public function where($ key,$ value = NULL,$ escape = TRUE)' - 第二个参数不是强制性的。 – alphacentauri