一、DB类增删改查
// 插入
DB::insert(
'insert into hd_user(username, password) values(?, ?)'
, [
'admin'
, 123456]);
// 查询
DB::select(
'select * from hd_user where username = ?'
, [
'admin'
]);
// 更新
DB::update(
'update hd_user set password= ? where username = ?'
, [654321,
'admin'
]);
// 删除
DB::
delete
(
'delete from hd_user where username = ?'
, [
'admin'
]);
聚合函数
$users = DB::table('users')->count();
$price = DB::table('orders')->max('price');
$price = DB::table('orders')->min('price');
$price = DB::table('orders')->avg('price');
$total = DB::table('users')->sum('votes');
二、查询构造器
1.从数据表中获取所有的数据列
$users = DB::table(
'users'
)->
get
();
2.
从数据表中获取单个列或行
$user = DB::table(
'users'
)->
where
(
'name'
,
'John'
)->first();
3.
从单行数据中取出单个值,使用 value 方法。
$email = DB::table(
'users'
)->
where
(
'name'
,
'John'
)->value(
'email'
);
4.
若你想要获取一个包含单个字段值的数组,你可以使用pluck方法
$titles = DB::table(
'roles'
)->pluck(
'title'
);
三 、model操作数据库
a. User::find(1) 查找单条数据
b. User::all() 查找所有数据
c. User::find(1)->delete() 删除单条数据
d. User::destory(array(1,2,3)) 删除单条或多条数据
e. User::save() 保存数据
f. User::first() 取第一条数据
g. Album::where('artist', '=', 'Matt Nathanson') ->update(array('artist' => 'Dayle Rees')); 指定查询条件,更新数据
h. User::truncate() 清空数据表,危险操作
i. Album::where('artist', '=', 'Something Corporate')->get(array('id','title')); 配合查询条件获取多条数据
j. Album::pluck('artist'); 返回表中该字段的第一条记录
k. Album::lists('artist'); 返回一列数据
l. Album::where('artist', '=', 'Something Corporate')->toSql(); 获取查询的sql语句,仅用于条件,不能用户带get()之类的带查询结果的查询中
// 插入
$user
=
new
User;
$user
->username =
'admin'
;
$user
->save();
// 查询
// 查询所有
User::get();
// 查询多条
User::where(
'age'
,
'>'
,
'20'
)->get();
// 查询一条
user::find(1);
// 更新
$user
= User::find(1);
// 查找主键为1的一条记录
$user
->username =
'new name'
;
$user
->save();
// 或者用 update() 方法
// 删除
// 方法1.先获取记录再删除
User::find(1)->
delete
();
// 方法2.通过主键直接删除
User::destroy(1, 2);
// 方法3.通过 where 条件删除
User::where(
'username'
,
'admin'
)->
delete
();