laravel 数据库操作小例子
public function demo()
{
$res = null;
//insert数据插入
//$user=array(‘username‘=>‘joy‘,‘password‘=>‘123456‘,‘age‘=>23);
//$res = DB::table(‘users‘)->insert($user);
/*
数据查询
$res = DB::table(‘users‘)->where(‘username‘,‘joy‘)->get();
$res = DB::select(‘SELECT * FROM users WHERE username="joy"‘);
*/
/*
更新数据
$res =DB::update(‘UPDATE users SET age=25 WHERE username="joy"‘);
$res =DB::table(‘users‘)->where(‘username‘,‘joy‘)->update(array(‘age‘ =>23));
*/
/*
删除数据
$res = DB::delete(‘DELETE FROM users WHERE username="joy"‘);
$res = DB::table(‘users‘)->where(‘username‘,‘joy‘)->delete();
*/
/*
字段添加
$res = DB::statement(‘ALTER TABLE users ADD sex tinyint(1) not null default 0‘);
*/
/*事务
DB::transaction(function(){
$user=array(xxxx);
DB::table(‘user‘)->insert($user);
DB.....
});
*/
/*结果查询器
$res = DB::table(‘users‘)->where(‘username‘,‘Qing‘)->pluck(‘age‘);//去特定字段值
$res = DB::table(‘users‘)->lists(‘age‘);//特殊字段list值
$res = DB::table(‘users‘)->select(array(‘id‘,‘username‘))->get();多个特殊字段查询
$res = DB::table(‘users‘)->where(‘id‘,‘>‘,1)->get();
$res = DB::table(‘users‘)->where(‘id‘,1)->get();
$res = DB::table(‘users‘)->whereId(1)->get();
//user_age->whereUserAge
$res = DB::table(‘users‘)->where(‘id‘,‘<‘,3)->where(‘username‘,‘Qing‘)->get();
$res = DB::table(‘users‘)->where(‘id‘,‘>‘,3)->orWhere(‘username‘,‘Qing‘)->get();
//username = Qing and (age>13 or sex=0)
$res = DB::table(‘users‘)->where(‘username‘,‘Qing‘)->where(function($query){
$query->where(‘age‘,‘>‘,13)->orWhere(‘sex‘,0);
})->get();
$res = DB::table(‘users‘)->whereBetween(‘age‘,array(0,15))->get();
$res = DB::table(‘users‘)->whereNotBetween(‘age‘,array(0,15))->get();
$res = DB::table(‘users‘)->whereIn(‘age‘,array(23,30))->get();
$res = DB::table(‘users‘)->whereNot In(‘age‘,array(23,30))->get();
*/
//$res = DB::table(‘users‘)->groupBy(‘sex‘)->orderBy(‘id‘,‘DESC‘)->having(‘sex‘,‘=‘,0)->get();
//$res = DB::table(‘users‘)->limit(2,3)->get();
//$res = DB::table(‘users‘)->skip(2)->take(1)->get();
//$res = DB::table(‘posts‘)->join(‘users‘,‘posts.user_id‘,‘=‘,‘users.id‘)->get();
// $res = DB::table(‘posts‘)->join(‘users‘,function($query){
// $query->on(‘posts.user_id‘,‘=‘,‘users.id‘);//->On(...);
// })->get();
/*
嵌套查询
$res = DB::table(‘users‘)->where(function($query){
if(Input::get(‘status‘)){
$query->whereStatus(Input::get(‘status‘));
}
if(Input::get(‘source‘)){
$query->whereSource(Input::get(‘source‘));
}
})->get();
*/
/*
$res = DB::table(‘users‘)->whereExists(function($query){
$query->select(‘*‘)->from(‘posts‘)->whereRaw(DB::raw(‘users.id = posts.user_id‘));
})->get();
*/
//$res = DB::table(‘users‘)->where(‘id‘,‘>‘,‘2‘)->count();
// $res = DB::table(‘posts‘)->where(‘id‘,6)->decrement(‘view_count‘,5);
// $res=DB::table(‘posts‘)->truncate();
//$res=DB::table(‘users‘)->where(‘id‘,‘>‘,2)->remember(0.2)->get();
echo "<pre>";
print_r($res);
echo "</pre>";
return ‘ok‘;
}