查询条件

我们定义了一套统一的查询条件语法,使用array作为查询条件,她兼容 MySQLMongodb 两种数据库驱动。未来还要兼容 ElasticSearch 的搜索语法。下面我们就具体说说怎么用这套查询语法实现各种查询。


//1. where name = 'xiaoming' AND age = 20
$conditions = array('name' => 'xiaoming', 'age' => 20);

//2. where name = 'xiaoming' AND age > 20
$conditions = array('name' => 'xiaoming', 'age' => '>20');
//也可以这样写的
$conditions = array('name' => 'xiaoming', 'age' => array('>' => 20));

//3. where name = 'xiaoming' AND age > 20 AND age < 30
$conditions = array('name' => 'xiaoming', 'age' => array('>' => 20, '<' => 30));

//4. where name = 'xiaoming' OR (age > 20 AND age < 30)
//如果想使用OR查询,在字段前面添加 | 就可以了
$conditions = array('name' => 'xiaoming', '|age' => array('>' => 24, '<' => 30));

//5. where name = 'xiaoming' OR (name='xiaoyang' AND address='shenzhen')
$conditions = array(
    'name' => 'xiaoming', 
    '$or' => array('name' => 'xiaoming', 'address' => 'shenzhen'));

//6. where name='xiaoming' OR !(address = 'shenzhen') 
$conditions = array('name' => 'xiaoming', '#address' => 'shenzhen')

//7. in查询 where address = 'shenzhen' AND id in(1, 2, 3)
$conditions = array('address' => 'shenzhen', 'id' => array('$in' => array(1, 2, 3)));
$conditions = array('id' => array('$in' => '1,2,3')); //这种方法也是可以的
// where address = 'shenzhen' AND name in('xiao3', 'xiao4', 'xiao5')
$conditions = array(
    'address' => 'shenzhen', 
    'name' => array('$in' => array('xiao3', 'xiao4', 'xiao5')));

// where address = 'shenzhen' AND name not in('xiao3', 'xiao4', 'xiao5');
$conditions = array(
    'address' => 'shenzhen', 
    'name' => array('$nin' => array('xiao2', 'xiao4', 'xiao5')) );

//8. where title like '%abc%'
$conditions = array('title' => '%abc%');

//9. where title is null
$conditions = array('title' => array('null' => 1);
// where title is not null
$conditions = array('title' => array('null' => -1));

特殊说明: 字段前面添加不同的连接符号代表不同的查询逻辑

  • | => OR 'OR' 查询
  • ! => AND ! 条件取反,并且用'AND'连接
  • # => OR ! 条件取反,并且用'OR'连接
  • & => AND 'AND' 查询

查询中我们定义了一些操作符号

  • $or 代表与前面的查询条件是'OR'的关系,而内部查询使用的'AND'的方
  • $in 使用in查询
  • $nin 使用not in查询
Copyright © HerosPHP 2016 all right reserved,powered by Gitbook最后更新时间: 2016-10-16 11:35:17

results matching ""

    No results matching ""