一。原生SQL操作数据库
在controller中对数据库进行增删改查的操作
public static function testDB(){
//增加一条数据
DB::insert(“insert into student(name,age) values(?,?)”,[‘sandy’,19]);
//删除一条数据
DB::delete(‘delete from student where name=?’,[‘sandy’]);
//修改一条数据
DB::update(‘update student set sex=? where name=?’,[‘男’,‘tory’]);
//查询数据
r
e
s
=
D
B
:
:
s
e
l
e
c
t
(
′
s
e
l
e
c
t
∗
f
r
o
m
s
t
u
d
e
n
t
′
)
;
/
/
进
行
数
据
库
通
用
操
作
D
B
:
:
s
t
a
t
e
m
e
n
t
(
′
d
r
o
p
t
a
b
l
e
u
s
e
r
s
′
)
;
/
/
打
印
结
果
d
d
(
res=DB::select('select * from student'); //进行数据库通用操作 DB::statement('drop table users'); //打印结果 dd(
res=DB::select(′select∗fromstudent′);//进行数据库通用操作DB::statement(′droptableusers′);//打印结果dd(res);
}
二。
3.2、增删改查
//增加一条数据
DB::table(‘student’)->insert([‘name’=>‘李four’,‘sex’=>‘男’,‘age’=>22]);
//增加多条数据
DB::table(‘student’)->insert([
[‘name’=>‘wang五’,‘sex’=>‘女’,‘age’=>21],
[‘name’=>‘zhao六’,‘sex’=>‘女’,‘age’=>20],
]);
//删除数据
DB::table(‘student’)->where(‘id’,’>=’,1006)->delete();
//删除整个表
DB::table(‘student’)->truncate();
//修改数据
DB::table(‘student’)->where(‘id’,1005)->update([‘sex’=>‘女’,‘age’=>21]);
//自增increment、自减decrement,默认增1
DB::table(‘student’)->where(‘id’,1005)->increment(‘age’,2);
//自增同时可以进行修改
DB::table(‘student’)->where(‘id’,1005)->increment(‘age’,1,[‘sex’=>‘女’]);
//查询指定字段
$res=DB::table(‘student’)->select(‘name’,‘age’)->get();
三。
通过查询构建器的where方法可以添加数据库查询条件,where()接收三个参数:字段名、操作符、值,操作符如果是’='可以省略
laravel查询构建器还提供了聚合函数用于操作查询的结果集,包括count(计数)、sum(求和)、avg(平均值)、max(最大值)、min(最小值),例如求年龄平均值: