链式操作


一、获取一条记录

  1. $db = Db::connect('timo');
  2. $user = $db->table('user')->where('id', 394835)->row();
  3. //指定字段
  4. $user = $db
  5. ->table('user')
  6. ->fields('id, name, avatar')
  7. ->where(['id' => 394835])
  8. ->row();

二、获取多条记录

获取全部

  1. $users = $db
  2. ->table('user')
  3. ->where(['certified' => 5, 'grade' => ['between', 2, 5]])
  4. ->select();

限制条数

  1. $users = $db->table('user')->where('id', '>', 5)->limit(10)->select();

三、分页获取

  1. $page = ['p' => 1, 'limit' => 20];
  2. $users = $db
  3. ->table('user')
  4. ->where(['certified' => 5, 'grade' => ['between', 2, 5]])
  5. ->order('id DESC')
  6. ->page($page)
  7. ->select();
  8. return App::result(0, 'ok', [
  9. 'users' => $users,
  10. 'page' => $page
  11. ]);

page说明

page里面的参数是引用传递,查询之后$page会在原来的基础上增加两个元素:

  1. $page == [
  2. 'p' => 1,
  3. 'limit' => 10,
  4. 'total' => 298,
  5. 'total_page' => 30
  6. ]

四、排序

  1. $users = $db
  2. ->table('user')
  3. ->where('certified', 5)
  4. ->where('grade', 'between', [2, 5])
  5. ->order('grade DESC, id DESC')
  6. ->select();

五、分组

  1. $users = $db
  2. ->table('user')
  3. ->fields('grade, count(*) num')
  4. ->where('certified', 5)
  5. ->where('grade', 'between', [2, 5])
  6. ->group('grade')
  7. ->select();

六、获取一列

返回某列值的数组

  1. $users = $db
  2. ->table('user')
  3. ->where('certified', 5)
  4. ->where('grade', 'between', [2, 5])
  5. ->column('nickname');
  6. //返回值如:
  7. Array
  8. (
  9. [0] => timo900
  10. [1] => timor
  11. [2] => oky
  12. )

返回以某个字段的值作为键,指定字段的值作为值的数组

  1. $users = $db
  2. ->table('user')
  3. ->where('certified', 5)
  4. ->where('grade', 'between', [2, 5])
  5. ->column('nickname', id);
  6. //返回值如:
  7. Array
  8. (
  9. [1] => timo
  10. [3] => tommy
  11. [4] => oky
  12. )

返回以某个字段的值作为键的二维数组

  1. $users = $db
  2. ->table('user')
  3. ->where('certified', 5)
  4. ->where('grade', 'between', [2, 5])
  5. ->column('nickname, avatar', id);
  6. //返回值如:
  7. Array
  8. (
  9. [1] => Array
  10. (
  11. [id] => 1
  12. [nickname] => timo
  13. [avatar] => 1234567890.jpg
  14. )
  15. [3] => Array
  16. (
  17. [id] => 3
  18. [nickname] => tommy
  19. [avatar] => b344.jpg
  20. )
  21. [4] => Array
  22. (
  23. [id] => 4
  24. [nickname] => oky
  25. [avatar] => 3984N.jpg
  26. )
  27. )

七、获取值

  1. $nickname = UserModel::where('id', 3)->value('nickname');
  2. //返回值如:tommy

八、关联查询

  1. join($table, $condition, $type = 'LEFT')
  2. INNER JOIN
  3. LEFT JOIN
  4. RIGHT JOIN
  5. FULL JOIN
  6. 第三个参数控制,默认LEFT JOIN
  1. $user = $db->table('user')->alias('u')
  2. ->fields('u.id, u.nickname, i.school')
  3. ->join('user_info i', 'u.id = i.uid')
  4. ->where('u.id', '<', 3)
  5. ->select();
  6. var_dump($db->getLastSql());
  7. // SELECT u.id, u.nickname, i.school FROM `user` u LEFT JOIN user_info i ON u.id = i.uid WHERE `u`.id < 3