Laravel学习记录--查询构造器

查询
1.获取单列数据 first() //返回对象的结果集

$res=DB::table('book')->where('bname','数学')->first();

2.获取具体字段值value() value必须指定值 //返回字符串
例:

$res = DB::table('book')->where('bname','数学')->value('bname');

3.获取一列的值 pluck() //pluck 必须指定值 //返回对象的数组 最多查询两个字段 以键值方式显示

$res = DB::table('book')->pluck('tid','test','bname');

常用聚合函数
1.统计
例:

$res = DB::table('book')->count('bid');

2.指定查询的字段
get()方法 返回对象的数组
例:

$res = DB::table('book')->select('bname','bid')->get();

3.查询不重复结果 (这里好像有点问题)
distinct() 方法
例:

$res = DB::table('book')->distinct()->get();

在已存在的查询添加查询

$res = DB::table('book')->select('bname');
$res = $res->addSelect('bid','tid')->get();

4.执行原生查询 //返回对象的数组
例:

$res = DB::select('select* from book')

对查询构造器加入原生查询

a.使用selectRaw 查询
b.使用whereRaw 条件
c.使用havingRaw

$res = DB::table('book')
->selectRaw('bname as title')
->groupBy('bid')
->havingRaw('bid>1')
->get();

连接查询
1.基本格式
DB::table(‘表1’)
->join(‘表2’,‘表1字段’,’=’,‘表2字段’)
->join(‘表3’,‘表1/表2字段’,’=’,‘表3字段’)

2.左右链接同理

$res = DB::table('book')
     ->join('teacher','book.tid','=','teacher.tid')
     ->join('zhichen','teacher.zid','=','zhichen.zid')
     ->where('book.tid',2)
     ->get();

联合查询
1.联合查询必须保证字段相同

$res1 = DB::table('book')->whereNull('bname');
$res =  DB::table('test')->unionall($res1)->get();

where语句
1.orWhere() 或者…
2.whereBetween(‘字段’,[范围区间]) 判断字段是否介于范围区间

例:whereBetween('age',[1,100])

3.whereNotBetween(‘字段’,[范围区间]) 判断字段不在两值之间
4.whereIn(‘字段’,[‘可选值’]) 判断字段是否在数组内
5.whereNotIn(‘字段’,[‘可选值’]) 判断指定不在数组内
6.whereNull 验证字段值为空
7.whereNotNull 验证字段不为空
8.whereDate(‘字段’,‘2019-9-9’) 比较字段的值和日期
9.whereMonth(‘字段’,‘月份’) 比较字段月份
10.whereDay(‘字段’,‘天’) 比较某一天
11.whereYear(‘字段’,‘年’) 比较年
12.whereTime(‘字段’,’=’,‘时间’) 比较特定时间
13.whereColumn(‘字段1’,‘字段2’) 比较两个字段是否相等

orderby语句
//orderBy(‘name’,‘desc/asc’)

latest() 和 oldest() 方法允许你轻松地按日期对查询结果排序。默认情况下是对 created_at 字段进行排序。

//inRandomOrder():将查询结果随机排序 可用于随机取人
分组groupBy

groupBy('字段')
having('tid','>' ,100)//条件

多个分组

groupBy('字段','字段2')
having('条件')

限制查询
skip(n)指定跳过查询中给定的数量的结果
take(n)指定取查询的几条结果
两个联合使用 案例 跳过3个取两个

DB::table('book')->skip(3)->take(2)->get()

limit/offset 相当于 原生sql “limit start(offset) length(limit)

插入insert
先设置fillable的允许批量添加的值
插入单行

DB::table('book')->insert('key'=>'value',....)

插入多行

insert(
[
  ['email'=>'df']
  ['email'=>'ds']
]
)

插入时获取自增id

DB::table()->insertGetId(['key'=>'value'])//只能插入一个值

更新update

update(['key'=>'value'])

字段自增&自减

DB::table()->increment('字段');//默认加1
DB::table()->increment('字段',3);//指定加3
DB::table()->decrement()//同理

指定条件自增

increment('字段',step,['条件'])

删除delete

->where()->delete()

清理数据表

DB::table()->truncate()
发布了17 篇原创文章 · 获赞 0 · 访问量 453

猜你喜欢

转载自blog.csdn.net/weixin_45143481/article/details/104010207
今日推荐