4 Db类:链式操作

知识梳理

链式方法    参数形式
where*(); 字符串 数组 对象 用于and查询
whereOr*() 字符串 数组 对象 用于or查询
whereTime*() 字符串 时间日期的快捷查询
table() 字符串 数组

field*()    要查询的字段  字符串和数组

limit(); 限制查询结果梳理 字符串和数组
order*(); 对结果排序 字符串和数组
alias();   当前数据表起别名 字符串
 
group()  字符串
having() 字符串
join*()   字符串和数组
union*()  字符串 数组 对象
distinct() 布尔值
page() 字符串 数字
 
所有带星号的表示支持多次调用

 

 

 

 

 

一 where方法官方推荐表达式

1)表达式形式参数

Db::table('bbs_category')->where('id','=',82')->where('status','=',1)->select();

2)关联数组

//主要用于等值and条件
Db::table('bbs_category')->where(['id' => 82, 'status' => 1])->select();
select * from bbs_category where id=82 and status=1;

3)索引数组

//批量设置查询条件
$where = [
    ['id','=',82],
    ['status','=',1]
];
Db::table('bbs_category')->where($where)->select();

3.1:组装查询条件

$where[] = ['id','=',82];
$where[] = ['status','=',1];

//var_dump($where);
array(2) {
    [0]=>
  array(3) {
        [0]=> string(2) "id"
        [1]=> string(1) "="
        [2]=> int(82)
  }
  [1]=>
  array(3) {
        [0]=> string(6) "status"
        [1]=> string(1) "="
        [2]=> int(1)
  }
}

4)字符串参数

Db::table('bbs_category')->whereRaw('id=82 AND status=1')->select();
注意使用字符串查询条件和表达式查询的一个区别在于,字符串参数不会对查询字段进行避免关键词冲突处理
使用字符串条件的时候,如果需要传入变量,建议配合预处理机制,确保更加安全
例如: Db::table('think_user') ->whereRaw("id=:id and username=:name",['id' => 1 , 'name' => 'thinkphp'])->select();

二 field() 方法

1)基础用法

//字符串参数
Db::table('bbs_category')->field('id,name as 中文姓名')->select();//字符串参数 别名支持中文

//数组参数
Db::table('bbs_category')->field(['id','name'=>'中文名称','pid'])->select();//数组参数 别名不支持中文
                        数组键值对是别名

//fieldRaw 方法中直接使用函数
Db::table('bbs_category')->fieldRaw('SUM(pid)')->select();

//获取所有字段
Db::table('user')->select();//不调用field()方法
Db::table('user')->field('*')->select();//用星号

//显示调用 不太明白
field(true) 的用法会显式的获取数据表的所有字段列表,哪怕你的数据表有100个字段。

 

 2)字段排除

字符串传参
Db::table('bbs_category')->withoutField('name,pid')->select();
数组传参
Db::table('bbs_category')->withoutField(['name','pid'])->select();

字段排除不支持跨表join查询

 

三 limit() 方法

 

posted @ 2020-12-30 21:10  棉花糖88  阅读(138)  评论(0)    收藏  举报