where条件怎么写


说明

where方法可以多次调用

一、根据主键查询

  1. $db->table('user')->where(100)->row(); //等价于where('id', 100)
  2. // SELECT * FROM `user` WHERE `id` = 100

二、查询表达式

  1. $db->table('user')
  2. ->fields('id, nickname, avatar')
  3. ->where('grade', '>', 4)
  4. ->where('status', 1) //等于可以简写成这种
  5. ->select();
  6. // SELECT id, nickname, avatar FROM `user` WHERE `grade` > 4 AND `status` = 1

更多查询表达式

  1. =、>、<、<>、>=、<=
  2. betweeninlikefind_in_set
  1. where('grade', 'between', [3, 5])
  2. where('id', 'in', [1,3,4,6,8])
  3. where('nickname', 'like', '%timo%')
  4. $db->table('user')->where('pids', 'find_in_set', 10)->select();

三、索引数组

  1. $db->table('user')
  2. ->where([
  3. ['grade', 'between', [3,5]],
  4. ['status', 1]
  5. ])->select();
  6. // SELECT * FROM `user` WHERE `grade` BETWEEN 3 AND 5 AND `status` = 1

四、关联数组

  1. $db->table('user')
  2. ->where(['grade' => ['between', 3, 5], 'status' => 1])
  3. ->select();
  4. // SELECT * FROM `user` WHERE `grade` BETWEEN 3 AND 5 AND `status` = 1

五、or条件查询

  1. 我们不推荐在项目中使用or查询

简单

  1. $user = $db->table('user')
  2. ->where('sex', 2)
  3. ->orWhere('sex', 0)
  4. ->select();
  5. var_dump($db->getLastSql());
  6. // SELECT * FROM `user` WHERE `sex` = 2 OR `sex` = 0

复杂

  1. $user = $db->table('user')
  2. ->where('sex', 2)
  3. ->orWhere(function () {
  4. return [
  5. 'sex' => 0,
  6. 'status' => 1
  7. ];
  8. })
  9. ->select();
  10. var_dump($db->getLastSql());
  11. // SELECT * FROM `user` WHERE `sex` = 2 OR (`sex` = 0 AND `status` = 1)