laravel框架总结(七) -- 数据库操作

1.使用DB门面进行基本操作

一旦你设置好了数据库连接,就可以使用 DB facade 来进行查找。DB facade 提供每个类型的查找方法:select、update、insert、delete、statement。
 
1.1增->
DB::insert('insert into users (id, name) values (?, ?)', [1, 'Dayle']);
1.2删->
$deleted = DB::delete('delete from users');
返回值:删除的行数将会被返回
 
1.3改->
$affected = DB::update('update users set votes = 100 where name = ?', ['John']);
返回值:该方法会返回此声明所影响的行数
 
1.4查->
$users = DB::select('select * from users where active = ?', [1]);
返回值:方法总会返回结果的数组数据。数组中的每个结果都是一个 PHP StdClass 对象,这使你能够访问到结果的值:
访问方法:
foreach ($users as $user) {
  echo $user->name;
}
 
1.5事务处理->
//自动
DB::transaction(function () {
  DB::table('users')->update(['votes' => 1]);   DB::table('posts')->delete(); }); //手动(可配合try catch使用) DB::beginTransaction(); if($someContion){   DB::rollback();   return false; } DB::commit();
1.6有时候一些数据库操作不应该返回任何参数。对于这种类型的操作,你可以在 DB facade 使用 statement 方法:
DB::statement('drop table users');

2.查询构造器

获取查询构建器很简单,还是要依赖DB门面,我们使用DB门面的table方法,传入表名,即可获取该表的查询构建器:
 
2.1获取结果
<1>从数据表中获取所有的数据列
$users = DB::table('users')->get();

返回值: 方法会返回一个数组结果,其中每一个结果都是 PHP StdClass 对象的实例

访问方法:
foreach ($users as $user) {
  echo $user->name;
}
 
<2>从数据表中获取单个列或行
1>若你只需从数据表中取出单行数据,则可以使用 first 方法。
$user = DB::table('users')->where('name', 'John')->first();
返回值:这个方法会返回单个 StdClass 对象: 使用方法:echo $user->name;
 
2>若你不想取出完整的一行,则可以使用 value 方法来从单条记录中取出单个值。
$email = DB::table('users')->where('name', 'John')->value('email');
返回值:这个方法会直接返回字段的值:
 
<3>从数据表中将结果切块
若你需要操作数千条数据库记录,则可考虑使用 chunk 方法。这个方法一次只取出一小「块」结果,并会将每个区块传给一个闭包进行处理。
例如,让我们将整个 user 数据表进行切块,每次处理 100 条记录:
DB::table('users')->chunk(100, function($users) {
  foreach ($users as $user) {     //   } });

你可以从闭包中返回 false,以停止对后续切块的处理:

DB::table('users')->chunk(100, function($users) {
  // 处理记录…   return false; });
<4>获取字段值列表
若你想要获取一个包含单个字段值的数组,你可以使用 lists 方法
$titles = DB::table('roles')->lists('title');
返回值:在这个例子中,我们将取出 role 数据表 title 字段的数组:
使用方法:
foreach ($titles as $title) {
  echo $title;
}
你也可以在返回的数组中指定自定义的键值字段:
$roles = DB::table('roles')->lists('title', 'name');
foreach ($roles as $name => $title) {   echo $title; }
2.2select的用法
1>指定一个 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();
2>原始表达式
//DB::raw 方法可以防止注入
$users = DB::table('users') ->select(DB::raw('count(*) as user_count, status')) ->where('status', '<>', 1) ->groupBy('status') ->get();
2.3join的用法
1>基本用法
$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,rightjoin替换join即可
2>高级的 Join 语法
你也可以指定更高级的 join 子句。让我们以传入一个闭包当作 join 方法的第二参数来作为开始。此闭包会接收 JoinClause 对象,让你可以在 join 子句上指定约束:
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();
这里要提一下如果闭包函数functiton(){}中5是个变量,我们需要传过去那么应该这样写
function ($join) use($num){   $join->on('users.id', '=', 'contacts.user_id') 
      ->where('contacts.user_id', '>', $num) };

如果没有use($num)外面的$num是没法传递到where子句的

2.4where的用法
1>基本用法
$users = DB::table('users')->where('votes', '=', 100)->get();
$users = DB::table('users')->where('name', 'like', 'T%')->get();
$users = DB::table('users')->where('votes', 100)->get(); //省略了等号 $users = DB::table('users')->where('votes', '>', 100) ->orWhere('name', 'John')->get(); $users = DB::table('users')->whereBetween('votes', [1, 100])->get(); //一个字段的值介于两个值之间 $users = DB::table('users')->whereNotBetween('votes', [1, 100])->get(); //一个字段的值落在两个值之外 $users = DB::table('users')->whereIn('id', [1, 2, 3])->get(); //字段的值包含在指定的数组之内 $users = DB::table('users')->whereNotIn('id', [1, 2, 3])->get(); //字段的值不包含在指定的数组之内 $users = DB::table('users')->whereNull('updated_at')->get(); //指定列的值为 NULL $users = DB::table('users')->whereNotNull('updated_at')->get(); //一个列的值不为 NULL
2>高级用法
将约束分组
DB::table('users') 
  ->where('name', '=', 'John')
  ->orWhere(function ($query) {     $query->where('votes', '>', 100)
        ->where('title', '<>', 'Admin');   }) ->get();
2.5orderBy,groupBy,having
$users = DB::table('users') ->orderBy('name', 'desc') ->get();
$users = DB::table('users') ->groupBy('account_id') ->having('account_id', '>', 100) ->get();
//havingRaw 方法可用来将原始字符串设置为 having 子句的值 $users = DB::table('orders') ->select('department', DB::raw('SUM(price) as total_sales')) ->groupBy('department') ->havingRaw('SUM(price) > 2500') ->get();
2.6insert的用法
DB::table('users')->insert( ['email' => 'john@example.com', 'votes' => 0] );
//可以一次插入多组数据
DB::table('users')->insert([ ['email' => 'taylor@example.com', 'votes' => 0], ['email' => 'dayle@example.com', 'votes' => 0] ]);
//若数据表有自动递增的 id,则可使用 insertGetId 方法来插入记录并获取其 ID: $id = DB::table('users')->insertGetId( ['email' => 'john@example.com', 'votes' => 0] );
2.7update的用法
DB::table('users') ->where('id', 1) ->update(['votes' => 1]);
2.8delete
DB::table('users')->delete();
DB::table('users')->where('votes', '<', 100)->delete();
//若你希望截去整个数据表的所有数据列,并将自动递增 ID 重设为零,则可以使用 truncate 方法:
DB::table('users')->truncate();

转载于:https://www.cnblogs.com/ghjbk/p/6638118.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值