构造器

分块结果

如果你需要处理上千条数据库记录,你可以考虑使用chunk方法,该方法一次获取结果集的一小块,并将其

传递给闭包,函数进行处理,该方法在artisan命令编写千条处理数据的时候非常有用,例如,我们可以将全部users

表数据切割成一次处理100条记录的一小块

DB::table('users')->orderBy('id')->chunk(100,function($users){

  foreach($users as $user){}

});

你可以通过 闭包 中返回false来终止继续获取分块结果

DB::table('users')->orderBy('id')->chunk(100,function($users){

  return false;

});

聚合

查询构造器还提供了各种聚合方法,比如 count max min avg 还有sum ,你可以在构造查询后调用任何方法

$users = DB::table('users')->count();

$price = DB::table('orders')->max('price');

你可以将这些聚合方法与其他的查询语句相结合

$prive = DB::table('orders')->where('fin',1)->avg('price');

判断记录是否存在

除了通过 count 方法可以确定查询条件的结果是否存在之外,还可以使用exists和 doestExist方法

return DB::table('orders')->where('f',1)->esists();

return DB::table('orders')->where('f',1)->doesntExist();

selects 指定一个 select 语句

当然你可能并不总是希望从数据库表中获取所有列,使用 select方法,你可以自定义一个select查询语句来查询指定

的字段

$users = DB::table('users')->select('name','email as user_email')->get();

distinct 方法会强制让查询返回的结果不重复

$users = DB::table('users')->distinct()->get();

如果你已经有了一个查询构造器实例,并且希望在现有的查询语句中加入一个字段,那么你可以使用 addSelect方法:

$query = DB::table('users')->select('name');

$users = $query->addSelect('age')->get();

原生表达式

有时候你可能需要在查询中使用原生表达式。你可以使用 DB::raw创建一个原生表达式

$users = DB::table('users')

->select(DB::raw('count(*) as user_count,status'))

->where('status','<>',1)

->groupBy('status')

->get();

可以使用以下方法代替DB::raw 将原生表达式插入查询的各个部分

selectRaw 方法可以代替 select(DB::raw(...)) .该方法的第二参数是可选项,值是一个绑定参数的数组

$orders = DB::table('orders')->selectRaw('price * ? as price_with_tax',[1.2222])->get();

whereRaw orWhereRaw havingRaw orHavingRaw

joins 

查询构造器也可以编写 join方法,若要执行基本的 内连接,你可以在查询构造器实例上使用 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();

left join 语句

如果你想使用 做链接代替内连接,可以使用leftJoin方法,leftJoin方法与join方法用法相同

$users = DB::table('users')->leftJoin('posts','users.id','=','posts.user_id')->get();

高级join语句

你可以指定更高级的join语句。比如传递一个闭包作为join方法的第二个参数,此闭包接收一个joinclause 对象

从而指定join语句中指定的约束

DB::table('users')->join('contains',function($join){

  $join->on('users.id','=','contacts.user_id')->orOn(...);

})

->get();

如果你想要在连接上使用where风格的语句,你可以在链接上使用where和orwhere方法,这些方法会将列和值进行

比较,而不是列和列进行比较

DB::table('users')->join('contains',function($join){

  $join->on('users.id','=','contacts.user_id')

})

->get();

子链接查询

你可以使用 joinSub leftJoinSub 和 rightJoinSub 方法关联一个查询作为子查询,他们每一种方法都会接收三个参数

子查询 表别名和定义关联字段的闭包

$latestPosts = DB::table('posts')

->select('user_id',DB::raw('MAX(create_at) as last_post_created_at'))

->where('is_published',true)

->groupBy('user_id');

$users = DB::table('users')

->joinSub($latestPosts,'latest_posts',function($join){

  $join->on('users.id','=','latest_posts.user_id');

})->get();

Unions 查询构造器还提供了将两个查询联合的快捷方式,比如,你可以先创建一个查询,然后使用union 方法

将其他和第二个查询进行联合

$first = DB::table('users')

->whereNull('first_name');

$users = DB::table('users')

->whereNull('last_name')

->union($first)

->get();

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();

你还可以传递条件数组到where函数中

$users = DB::table('users')->where([

  ['status','=','1'],

  ['sub','<>','1']

])->get();

Or语句

你可以一起链式调用where约束,也可以在查询中添加or字句,orWhere方法和where方法接收的参数一样

$users = DB::table('users')->where('votes','>',100)->orWhere('name','John')->get();

其他where语句

whereBetween 方法验证字段值是否在给定的两个值之间

$users = DB::table('users')->whereBetween('votes',[1,100])->get();

whereNotBetween 方法验证字段值是否在给定的两个值之外

$users = DB::table('users')->whereNotBetween('votes',[1,100])->get();

whereIn whereNotIn

whereNull whereNotNull

whereDate whereMonth whereDay whereYear whereTime

whereColumn  方法用于比较两个字段的值是否相等

$users = DB::table('users')->whereColumn('first_name','last_name')->get();

也可以传入一个比较运算符

$users = DB::table('users')->whereColumn('update_at','>','create_at')

->get();

orderBy

方法允许你通过给定字段对结果集进行排序,orderBy的第一个参数应该是你希望排序的字段,第二个参数控制排序的方向,可以是 asc 或

desc

$users = DB::table('users')->orderBy('name','desc')->get();

latest/oldest 方法可以使你轻松的通过日期排序,它默认使用 create_at 列作为排序依据。当然,你也可以传递

自定义的列名

$user = DB::table('users')->latest()->first();

inRandomOrder 方法被用来将结果随机排序。例如,你可以使用此方法随机找到一个用户。

$randomUser = DB::table('users')

->inRandomOrder()

->first();

groupBy 和 having方法可以将结果分组。having方法的使用过与where方法十分相似

$users = DB::table('users')->groupBy('account_id')->having('account_id','>',100)->get();

skip take 跳过指定数量的结果或限制结果的返回数量

$users = DB::table('users')->skip(10)->take(5)->get();

或者你也可以使用 limit 和offset方法

$users = DB::table('users')->offset(10)->limit(5)->get();

条件语句

有时候你可能想要字句只适用于某个情况为真时才执行查询,

$role = $request->input('role');

$users = DB::table('userts')

->where($role,function($quest,$role){

  return $quest->where('role_id',$role)

})

->get();

when方法只有在第一个参数为true的时候才执行给的闭包。如果第一个参数为false,那么这个闭包将不会被执行

你可以传递两一个闭包作为when方法的第三个参数。该闭包会在第一个参数为false的情况下执行。为了说明如何使用这个特性

,我们来配置一个查询的默认排序;

$sortBy = null;

$users = DB::table('userts')->when($sortBy,function($query,$sortBy){

  return $query->orderBy($sortBy);

},function($query){

  return $query->orderBy('name');

})

->get();

插入 查询构造器还提供了insert 方法用于插入记录到数据库中,insert方法接收数组形式的字段名和字段值进行插入

操作:

DB::table('users')->insert(['email'=>'john@example.com','votes'=>0]);

将多个记录插入到表中

DB::table('users')->insert([

  [],

  []

]);

自增ID

如果数据表有自增ID,使用insertGetId,方法来插入记录并返回ID值

$id = DB::table('users')->insertGetId(

  ['email'=>'john@example.com','votes'=>0]

);

更新 update

DB::table('users')->where('id',1)->update(['votes'=>1]);

自增与自减

->increment('votes')

->increment('votes',5)

->decrement('votes')

也可以在操作过程中指定要更新的字段

->increment('votes',1['name'=>'john'])

删除 delete 

->delete()

清空表 truncate()

sharedLock()

lockForUpdate()

原文地址:https://www.cnblogs.com/simadongyang/p/10237759.html