💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
[TOC] # 基本用法 注意这边from后面要跟完整的表名,就算.env文件配置过了也不行 ~~~ //DB命名空间是use Illuminate\Support\Facades\DB; //查询 $result=DB::select('select * from blog_stu'); //增加 $result=DB::insert('insert into blog_stu(name,age) values(?,?)',['sean',18]); //更新 $result=DB::update('update blog_stu set age=? where name=?',[21,'sean']); //查询 $result=DB::select('select * from blog_stu where id>?',[2]); //删除 $result=DB::delete('delete from blog_stu where id>?',[3]); //添加一条数据并获取自动递增的id号 $id = DB::table('users')->insertGetId(['email'=>'shuoshuo', 'pass'=>'2121']); ~~~ ![](https://box.kancloud.cn/aa984fb3ec658367c286579de78c2a79_1162x826.png) ~~~ first 方法是取得结果集数组中第一列数据,如果结果集为空则返回 null 。 pluck 方法是取得结果集第一列特定字段,它返回是字符串; lists 方法是按照 key=>value 对的方式返回数组;它的参数最多两个,第一个参数作为键值(value),第二个参数作为键名(key) ~~~ # 条件子句 有时我们只想在某些条件成立的时候呢才去执行一些条件子句查询。比如,对于 where 子句,我们只想在输入数据里包含某个字段的时候,才去执行,那么这时就要用到 when 了。 ~~~ $role = $request->input('role'); $users = DB::table('users') ->when($role, function ($query) use ($role) { return $query->where('role_id', $role); }) ->get(); ~~~ 在上面这段代码里,只有当闭包的第一个参数($role)判定为 true 时才会执行。如果第一个参数的判定值是 false,那么就不会执行闭包里的内容。 when 方法还接受第三个参数,跟第二个参数一样,也是一个闭包——当判定条件(第一个参数)为 false 时,就会执行这里的逻辑。为了说明这个方法的使用场景,我们来举一个配置默认使用的排序字段的例子: ~~~ $sortBy = null; $users = DB::table('users') ->when($sortBy, function ($query) use ($sortBy) { return $query->orderBy($sortBy); }, function ($query) { return $query->orderBy('name'); }) ->get(); ~~~ 当你在使用where语句有前提条件时,比如某值为1的时候才执行where子句,否则不执行,这个时候,laravel5.5新出了一个简便方法when($arg,fun1\[,fun2\])。 具体用法如下:当$arg为真时,执行闭包fun1,为假时,执行闭包fun2(可选); ~~~ when($arg,function ($q){ return $q->orderBy('id', 'asc'); }, function ($q) use ($a){ return $q->orderBy($a, 'desc'); }); ~~~ 当$arg为真是,执行按id升序排序,当$a为假时,执行按$a降序排序 # 查询构造器 不要写完整表名了,完整表名的blog_stu,然后.env文件里面配置过表名的前缀了 ~~~ //增加(返回主键id) $bool=DB::table('stu')->insertGetId( ['name'=>'yabo','age'=>23] ); //当前插入的主键id $bool=DB::table('stu')->insert( ['name'=>'yaboo','age'=>23] ); //成功返回true $nm=DB::table('stu')->insert([ ['name'=>'name1','age'=>17], ['name'=>'name2','age'=>18], ['name'=>'name3','age'=>19], ]); ~~~ ~~~ //更新 $bool=DB::table('stu')->where('id',8) ->update(['age'=>20]); //成功返回1 ~~~ ~~~ //删除(切记带where条件) $num=DB::table('stu')->where('id',8) ->delete(); //成功返回1 //如果要清空一个表可以这样,但是很危险 $nm=DB::table('stu')->truncate(); //null 成功了 ~~~ # 自增自减 ~~~ //数据库一共5条数据,全部把年龄自增1 $bool=DB::table('stu')->increment('age');//返回5 //上面代码想自增3 $bool=DB::table('stu')->increment('age',3);//返回5 //上面代码想自减3 $bool=DB::table('stu')->decrement('age',3);//返回5 //加条件 $bool=DB::table('stu')->where('id',6)->decrement('age',3,['name'=>'jdxia']);//返回1 ~~~ # 查询数据 ~~~ //get获取的意思,这是获取所有的数据 $nm=DB::table('stu')->get(); //取出第一条数据 $nm=DB::table('stu')->orderBy('id','desc')->first(); //where(单个条件) $nm=DB::table('stu')->where('id','>=',3)->get(); //where(给where加多个条件) $nm=DB::table('stu')->whereRaw('id>=? and age>?',[3,19])->get(); //pluck返回结果集指定的字段,返回只有name字段 $nm=DB::table('stu')->pluck('name'); //lists(上面的pluck返回结果加上以...为指定下标) $nm=DB::table('stu')->lists('name','id'); //select (查询的时候不想查询出所有的数据只想查询出指定的字段) $nm=DB::table('stu')->select('id','name')->get(); //chunk 每次查询2条,依次查询出来,或者手动return $nm=DB::table('stu')->chunk(2,function($students){ print_r($students); //if(你的条件) return false; }); ~~~ # 聚合函数 ~~~ //统计 $nm=DB::table('stu')->count(); //最大值 $nm=DB::table('stu')->max('age'); //最小值 $nm=DB::table('stu')->min('age'); //平均值 $nm=DB::table('stu')->avg('age'); //和 $nm=DB::table('stu')->sum('age'); ~~~ # 连接查询 ## 内连接(等值连接) 查询构建器还可以用于编写基本的 SQL “内连接”,你可以使用查询构建器实例上的 join 方法,传递给 join 方法的第一个参数是你需要连接到的表名,剩余的其它参数则是为连接指定的列约束,当然,正如你所看到的,你可以在单个查询中连接多张表: ~~~ $users = DB::table('users') ->join('contacts', 'users.id', '=', 'contacts.user_id') ->join('orders', 'users.id', '=', 'orders.user_id') ->select('users.*', 'contacts.phone', 'orders.price') ->get(); ~~~ ## 左连接 如果你是想要执行“左连接”而不是“内连接”,可以使用 leftJoin 方法。该方法和 join 方法的用法一样: ~~~ $users = DB::table('users') ->leftJoin('posts', 'users.id', '=', 'posts.user_id') ->get(); ~~~ ## 交叉连接 要执行“交叉连接”可以使用 crossJoin 方法,传递你想要交叉连接的表名到该方法即可。交叉连接在第一张表和被连接表之间生成一个笛卡尔积: ~~~ $users = DB::table('sizes') ->crossJoin('colours') ->get(); ~~~ ## 联合(union) 查询构建器还提供了“联合”两个查询的快捷方式,比如,你可以先创建一个查询,然后使用 union 方法将其和第二个查询进行联合: ~~~ $first = DB::table('users') ->whereNull('first_name'); $users = DB::table('users') ->whereNull('last_name') ->union($first) ->get(); ~~~ # 悲观锁 「悲观锁」作用在 select 语句上,如果要使用「共享锁」运行语句,可以在查询上使用 sharedLock 方法。共享锁可以保证用户 在读取数据时,除非事务提交,否则 数据不会被修改。 ~~~ DB::table('users')->where('votes', '>', 100)->sharedLock()->get(); ~~~ 还有一个 lockForUpdate 方法,比 sharedLock 还厉害——可以保证用户 在读取数据时,保证数据不被修改或被另一个共享锁所选择。 ~~~ DB::table('users')->where('votes', '>', 100)->lockForUpdate()->get(); ~~~ ## 其他常见用法 latest / oldest ``` latest / oldest 方法实现字段按照日期便捷地排序。默认是依据 created_at 字段排序的,你也可以传递要排序的字段名以便覆盖默认设定: $user = DB::table('users') ->latest() ->first(); $user = DB::table('users') ->latest('updated_at') ->first(); ``` groupBy / having / havingRaw groupBy 和 having 方法可以用来给查询结果进行分组。having 方法的签名类似 where 方法: ``` $users = DB::table('users') ->groupBy('account_id') ->having('account_id', '>', 100) ->get(); ``` havingRaw 方法用来设置原生字符串到 having 子句中。 例如,我们可以找到所有销售额大于 2500刀 的部门: ``` $users = DB::table('orders') ->select('department', DB::raw('SUM(price) as total_sales')) ->groupBy('department') ->havingRaw('SUM(price) > 2500') ->get(); ``` ## JSON Where 子句 Laravel 也支持数据库 JSON 字段类型的查询,前提是数据库支持 JSON 字段类型。现在 MySQL 5.7 和 Postgres 都支持。查询 JSON 字段,使用 -> 操作符: ~~~ $users = DB::table('users') ->where('options->language', 'en') ->get(); $users = DB::table('users') ->where('preferences->dining->meal', 'salad') ->get(); ~~~ ## 日期where whereDate / whereMonth / whereDay / whereYear whereDate 用来比较字段值是否满足给定的日期。 ~~~ $users = DB::table('users') ->whereDate('created_at', '2016-12-31') ->get(); ~~~ whereMonth 用来比较字段值是否满足给定的月份。 ~~~ $users = DB::table('users') ->whereMonth('created_at', '12') ->get(); ~~~ whereDay 用来比较字段值是否满足给定的日期。 ~~~ $users = DB::table('users') ->whereDay('created_at', '31') ->get(); ~~~ whereYear 用来比较字段值是否满足给定的年份。 ~~~ $users = DB::table('users') ->whereYear('created_at', '2016') ->get(); ~~~ whereBetween限制范围 ~~~ whereBetween('created_at',[date('Y-m-d').' 00:00:00',date('Y-m-d').' 23:59:59']) ~~~