laravel5.2增删改查和常用方法

一、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 ();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值