Laravel查询构建器基础与检索操作
一、Selects
检索表中的所有行 复制代码 代码如下: $users = DB::table('users')->get(); foreach ($users as $user) { var_dump($user->name); }
从表中获取单行记录 复制代码 代码如下: $user = DB::table('users')->where('name', 'John')->first(); var_dump($user->name); 检索包含单个列的行 复制代码 代码如下: $name = DB::table('users')->where('name', 'John')->pluck('name'); 获取特定列值的列表 复制代码 代码如下: $roles = DB::table('roles')->lists('title'); 该方法返回一个包含标题的数组。你也可以指定一个自定义的键列来作为返回数组的索引 复制代码 代码如下: $roles = DB::table('roles')->lists('title', 'name'); 指定Select子句 复制代码 代码如下: $users = DB::table('users')->select('name', 'email')->get(); $users = DB::table('users')->distinct()->get(); $users = DB::table('users')->select('name as user_name')->get();
向现有查询添加Select子句$query = DB::table('users')->select('name'); 复制代码 代码如下: $users = $query->addSelect('age')->get();
where 复制代码 代码如下: $users = DB::table('users')->where('votes', '>', 100)->get();
OR 复制代码 代码如下: $users = DB::table('users')->where('votes', '>', 100)->orWhere('name', 'John')->get();
Where Between
复制代码 代码如下: $users = DB::table('users')->whereBetween('votes', array(1, 100))->get();
Where Not Between
复制代码 代码如下: $users = DB::table('users')->whereNotBetween('votes', array(1, 100))->get();
Where In With An Array
复制代码 代码如下: $users = DB::table('users')->whereIn('id', array(1, 2, 3))->get(); $users = DB::table('users')->whereNotIn('id', array(1, 2, 3))->get();
Using Where Null To Find Records With Unset Values 复制代码 代码如下: $users = DB::table('users')->whereNull('updated_at')->get();
Order By, Group By, And Having 复制代码 代码如下: $users = DB::table('users')->orderBy('name', 'desc')->groupBy('count')->having('count', '>', 100)->get();
Offset & Limit
复制代码 代码如下: $users = DB::table('users')->skip(10)->take(5)->get();
二、连接
Joins
查询构建器同样支持编写连接语句。参考以下示例:
Basic Join Statement
复制代码 代码如下: DB::table('users') ->join('contacts', 'users.id', '=', 'contacts.user_id') ->join('orders', 'users.id', '=', 'orders.user_id') ->select('users.id', 'contacts.phone', 'orders.price') ->get();
左连接语句
复制代码 代码如下: DB::table('users') ->leftJoin('posts', 'users.id', '=', 'posts.user_id') ->get(); DB::table('users') ->join('contacts', function($join) { $join->on('users.id', '=', 'contacts.user_id')->orOn(...); }) ->get(); DB::table('users') ->join('contacts', function($join) { $join->on('users.id', '=', 'contacts.user_id') ->where('contacts.user_id', '>', 5); }) ->get();
三、分组
有时需要创建更高级的Where子句,例如“存在”检查或嵌套参数分组。Laravel查询构建器能够处理这些复杂逻辑:
复制代码 代码如下: DB::table('users') ->where('name', '=', 'John') ->orWhere(function($query) { $query->where('votes', '>', 100) ->where('title', '<>', 'Admin'); }) ->get(); 上述查询将生成如下SQL: 复制代码 代码如下: select * from users where name = 'John' or (votes > 100 and title <> 'Admin') Exists Statements DB::table('users') ->whereExists(function($query) { $query->select(DB::raw(1)) ->from('orders') ->whereRaw('orders.user_id = users.id'); }) ->get();
上述查询生成的SQL如下: 复制代码 代码如下: select * from userswhere exists ( select 1 from orders where orders.user_id = users.id )
四、聚合
查询构建器提供了多种聚合方法,包括统计数量、最大值、最小值、平均值和总和等。
Using Aggregate Methods 复制代码 代码如下: $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');
Raw Expressions
有时需要使用原始表达式进行查询。这些表达式会直接注入查询字符串,因此需小心避免SQL注入风险!可使用DB:raw方法创建原始表达式:
Using A Raw Expression
复制代码 代码如下: $users = DB::table('users') ->select(DB::raw('count(*) as user_count, status')) ->where('status', '<>', 1) ->groupBy('status') ->get();
递增或递减某列的值 复制代码 代码如下: DB::table('users')->increment('votes'); DB::table('users')->increment('votes', 5); DB::table('users')->decrement('votes'); DB::table('users')->decrement('votes', 5);
还可以指定额外的列进行更新: 复制代码 代码如下: DB::table('users')->increment('votes', 1, array('name' => 'John'));
Inserts
将记录插入表
复制代码 代码如下: DB::table('users')->insert( array('email' => 'john@example.com', 'votes' => 0) );
将记录插入表并获取自动增加的ID
如果表具有自动递增的id字段,可使用insertGetId插入记录并检索该ID: 复制代码 代码如下: $id = DB::table('users')->insertGetId( array('email' => 'john@example.com', 'votes' => 0) );
注意: 当使用PostgreSQL时,insertGetId方法预期自增列名为“id”。
向表中插入多条记录 复制代码 代码如下: DB::table('users')->insert(array( array('email' => 'taylor@example.com', 'votes' => 0), array('email' => 'dayle@example.com', 'votes' => 0), ));
四、Updates
更新表中的记录 复制代码 代码如下: DB::table('users') ->where('id', 1) ->update(array('votes' => 1));
五、 Deletes
删除表中的记录 复制代码 代码如下: DB::table('users')->where('votes', '<', 100)->delete();
删除表中的所有记录 复制代码 代码如下: DB::table('users')->delete(); 删除整个表 复制代码 代码如下: DB::table('users')->truncate();
六、Unions
查询构建器提供了一种快速的方法来“联合”两个查询:
复制代码 代码如下: $first = DB::table('users')->whereNull('first_name'); $users = DB::table('users')->whereNull('last_name')->union($first)->get();
unionAll方法也可用,且具有相同的签名。
Pessimistic Locking
查询构建器包含一些“悲观锁定”功能,有助于优化SELECT语句的执行。运行SELECT语句时使用“共享锁”,可通过sharedLock方法实现: 复制代码 代码如下: DB::table('users')->where('votes', '>', 100)->sharedLock()->get(); 在SELECT语句中使用“更新锁”,可通过lockForUpdate方法实现: 复制代码 代码如下: DB::table('users')->where('votes', '>', 100)->lockForUpdate()->get();
七、缓存查询
你可以轻松地使用记忆法缓存查询结果: 复制代码 代码如下: $users = DB::table('users')->remember(10)->get(); 在本例中,查询结果将被缓存十分钟。当查询结果被缓存时,不会再次执行数据库查询,而是从应用程序指定的默认缓存驱动加载结果。如果使用支持缓存标签的驱动,还可以为缓存添加标签: 复制代码 代码如下: $users = DB::table('users')->cacheTags(array('people', 'authors'))->remember(10)->get();