[ Laravel 5.2 文档 ] 数据库 —— 查询构建器
2016-09-23 09:38
357 查看
从一张表中取出所有行
在查询之前,使用DB门面的
table方法,
table方法为给定表返回一个查询构建器,允许你在查询上链接更多约束条件并最终返回查询结果。在本例中,我们使用
get方法获取表中所有记录:
<?php namespace App\Http\Controllers; use DB; use App\Http\Controllers\Controller; class UserController extends Controller{ /** * 显示用户列表 * * @return Response */ public function index() { $users = DB::table('users')->get(); return view('user.index', ['users' => $users]); } }和原生查询一样,
get方法返回结果集的数组,其中每一个结果都是PHP对象的
StdClass实例。你可以像访问对象的属性一样访问列的值:
foreach ($users as $user) { echo $user->name; }
从一张表中获取一行/一列
如果你只是想要从数据表中获取一行数据,可以使用first方法,该方法将会返回单个
StdClass对象:
$user = DB::table('users')->where('name', 'John')->first(); echo $user->name;如果你不需要完整的一行,可以使用value方法从结果中获取单个值,该方法会直接返回指定列的值:
$email = DB::table('users')->where('name', 'John')->value('email');
从一张表中获取组块结果集
如果你需要处理成千上百条数据库记录,可以考虑使用chunk方法,该方法一次获取结果集的一小块,然后填充每一小块数据到要处理的闭包,该方法在编写处理大量数据库记录的 Artisan 命令的时候非常有用。比如,我们可以将处理全部 users 表数据处理成一次处理 100 记录的小组块:
DB::table('users')->chunk(100, function($users) { foreach ($users as $user) { // } });你可以通过从闭包函数中返回false来中止组块的运行:
DB::table('users')->chunk(100, function($users) { // 处理结果集... return false; });
获取数据列值列表
如果想要获取包含单个列值的数组,可以使用lists方法,在本例中,我们获取所有
title的数组:
$titles = DB::table('roles')->lists('title'); foreach ($titles as $title) { echo $title; }在还可以在返回数组中为列值指定更多的自定义键(该自定义键必须是该表的其它字段列名,否则会报错):
$roles = DB::table('roles')->lists('title', 'name'); foreach ($roles as $name => $title) { echo $title; }
聚合函数
队列构建器还提供了很多聚合方法,比如count,
max,
min,
avg, 和
sum,你可以在构造查询之后调用这些方法:
$users = DB::table('users')->count(); $price = DB::table('orders')->max('price');当然,你可以联合其它查询子句和聚合函数来构建查询:
$price = DB::table('orders') ->where('finalized', 1) ->avg('price');
3、查询(Select)
指定查询子句
当然,我们并不总是想要获取数据表的所有列,使用select方法,你可以为查询指定自定义的
select子句:
$users = DB::table('users')->select('name', 'email as user_email')->get();
distinct方法允许你强制查询返回不重复的结果集:
$users = DB::table('users')->distinct()->get();如果你已经有了一个查询构建器实例并且希望添加一个查询列到已存在的
select子句,可以使用
addSelect方法:
$query = DB::table('users')->select('name'); $users = $query->addSelect('age')->get();
原生表达式
有时候你希望在查询中使用原生表达式,这些表达式将会以字符串的形式注入到查询中,所以要格外小心避免被 SQL 注入。想要创建一个原生表达式,可以使用DB::raw方法:
$users = DB::table('users') ->select(DB::raw('count(*) as user_count, status')) ->where('status', '<>', 1) ->groupBy('status') ->get();
4、连接(Join)
内连接(等值连接)
查询构建器还可以用于编写基本的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();
高级连接语句
你还可以指定更多的高级连接子句,传递一个闭包到join方法作为该方法的第2个参数,该闭包将会返回允许你指定
join子句约束的
JoinClause对象:
DB::table('users') ->join('contacts', function ($join) { $join->on('users.id', '=', 'contacts.user_id')->orOn(...); }) ->get();如果你想要在连接中使用“where”风格的子句,可以在查询中使用
where和
orWhere方法。这些方法将会将列和值进行比较而不是列和列进行比较:
DB::table('users') ->join('contacts', function ($join) { $join->on('users.id', '=', 'contacts.user_id') ->where('contacts.user_id', '>', 5); }) ->get();
5、联合(Union)
查询构建器还提供了一条“联合”两个查询的快捷方式,比如,你要创建一个独立的查询,然后使用union方法将其和第二个查询进行联合:
$first = DB::table('users') ->whereNull('first_name'); $users = DB::table('users') ->whereNull('last_name') ->union($first) ->get();
unionAll方法也是有效的,并且和
union有同样的使用方法。
6、Where子句
简单where子句
使用查询构建器上的where方法可以添加
where子句到查询中,调用
where最基本的方法需要三个参数,第一个参数是列名,第二个参数是一个数据库系统支持的任意操作符,第三个参数是该列要比较的值。例如,下面是一个验证“votes”列的值是否等于100的查询:
$users = DB::table('users')->where('votes', '=', 100)->get();为了方便,如果你只是简单比较列值和给定数值是否相等,可以将数值直接作为
where方法的第二个参数:
$users = DB::table('users')->where('votes', 100)->get();当然,你可以使用其它操作符来编写
where子句:
$users = DB::table('users') ->where('votes', '>=', 100) ->get(); $users = DB::table('users') ->where('votes', '<>', 100) ->get(); $users = DB::table('users') ->where('name', 'like', 'T%') ->get();
or
你可以通过方法链将多个where约束链接到一起,也可以添加
or子句到查询,
orWhere方法和
where方法接收参数一样:
$users = DB::table('users') ->where('votes', '>', 100) ->orWhere('name', 'John') ->get();
更多Where子句
[b]whereBetween[/b]whereBetween方法验证列值是否在给定值之间:
$users = DB::table('users') ->whereBetween('votes', [1, 100])->get();[b]whereNotBetween[/b]
whereNotBetween方法验证列值不在给定值之间:
$users = DB::table('users') ->whereNotBetween('votes', [1, 100]) ->get();[b]whereIn/whereNotIn[/b]
whereIn方法验证给定列的值是否在给定数组中:
$users = DB::table('users') ->whereIn('id', [1, 2, 3]) ->get();
whereNotIn方法验证给定列的值不在给定数组中:
$users = DB::table('users') ->whereNotIn('id', [1, 2, 3]) ->get();[b]whereNull/whereNotNull[/b]
whereNull方法验证给定列的值为NULL:
$users = DB::table('users') ->whereNull('updated_at') ->get();
whereNotNull方法验证给定列的值不是NULL:
$users = DB::table('users') ->whereNotNull('updated_at') ->get();
高级Where子句
[b]参数分组[/b]有时候你需要创建更加高级的where子句比如“where exists”或者嵌套的参数分组。Laravel查询构建器也可以处理这些。作为开始,让我们看一个在括号中进行分组约束的例子:
DB::table('users') ->where('name', '=', 'John') ->orWhere(function ($query) { $query->where('votes', '>', 100) ->where('title', '<>', 'Admin'); }) ->get();正如你所看到的,传递闭包到
orWhere方法构造查询构建器来开始一个约束分组,,该闭包将会获取一个用于设置括号中包含的约束的查询构建器实例。上述语句等价于下面的SQL:
select * from users where name = 'John' or (votes > 100 and title <> 'Admin')[b]exists语句[/b]
whereExists方法允许你编写
where existSQL子句,
whereExists方法接收一个闭包参数,该闭包获取一个查询构建器实例从而允许你定义放置在“exists”子句中的查询:
DB::table('users') ->whereExists(function ($query) { $query->select(DB::raw(1)) ->from('orders') ->whereRaw('orders.user_id = users.id'); }) ->get();上述查询等价于下面的SQL语句:
select * from users where exists ( select 1 from orders where orders.user_id = users.id )
7、排序、分组、限定
orderBy
orderBy方法允许你通过给定列对结果集进行排序,
orderBy的第一个参数应该是你希望排序的列,第二个参数控制着排序的方向——asc或desc:
$users = DB::table('users') ->orderBy('name', 'desc') ->get();
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();
skip / take
想要限定查询返回的结果集的数目,或者在查询中跳过给定数目的结果,可以使用skip和
take方法:
$users = DB::table('users')->skip(10)->take(5)->get();
相关文章推荐
- Laravel 数据库实例教程 —— 使用查询构建器实现对数据库的高级查询
- Laravel学习笔记(五)---操作数据库--查询构建器(Query Builder)
- Laravel 数据库实例教程 —— 使用查询构建器对数据库进行增删改查
- laravel数据库 —— 查询构建器
- Laravel大量数据库查询导致php进程内存耗尽
- Laravel使用Caching缓存数据减轻数据库查询压力的方法
- CodeIgniter框架将数据库查询结果导出为.csv或.cvs或excel文档
- Laravel中的数据库查询教程
- 数据库查询构建控件集Active Query Builder
- Yii2.0-advanced-10—数据库操作2(查询构建器)
- MongoEngine文档 新手教程 查询数据库
- 数据库查询构建控件集Active Query Builder
- laravel使用Caching缓存数据减轻数据库查询压力
- 初级laravel 数据库操作之 查询构造器
- Laravel中的数据库查询教程
- laravel5.2中文文档
- laravel使用Caching缓存数据减轻数据库查询压力
- MongoEngine文档翻译__新手教程(四)查询数据库
- 构建施耐德楼控系统数据库后台服务器示例工程二(数据库查询编写)
- laravel中把查询数据库的sql写入日志中