1.常用的where查询,经常使用闭包来查询 不确定的的数据
DB::table('users')->where('name', '=', 'John') ->orWhere($role, function ($query) { $query->where('votes', '>', 100) ->where('title', '<>', 'Admin'); })
2.where 直接 条件
->whereRaw('price > IF(state = "TX", ?, 100)', [200])
3.如何不使用获取器,得到时间 和保留两位小数.
Send::from('hb_send as s') ->join('hb_received as r', 's.pass_id', '=', 'r.redpack_id') ->where(array('r.status' => 1,'r.open_id' => $this->_open_id)) ->select('r.redpack_id','r.id as rece_id','s.id as send_id', 'r.red_type','s.pass_id','s.is_square', (DB::raw("FROM_UNIXTIME(r.add_time,'%Y-%m-%d %H:%i:%s') as add_time")), (DB::raw("Convert(r.money,decimal(10,2)) as money")) ) ->orderBy('r.add_time', 'desc') ->paginate(10);
4.whereNotNull
方法验证字段的值不为 NULL
:
->whereNotNull('updated_at') ->get();
5.whereColumn
方法用于验证两个字段是否相等:
$users = DB::table('users') ->whereColumn('first_name', 'last_name') ->get();
6.whereExists
方法允许你编写where exists
SQL 语句。 该whereExists
方法接受一个Closure
参数,该闭包获取一个查询构建器实例从而允许你定义放置在 "exists" 字句中查询:
DB::table('users') ->whereExists(function ($query) { $query->select(DB::raw(1)) ->from('orders') ->whereRaw('orders.user_id = users.id'); }) ->get();
insertGetId 方法将默认把 id
作为自动递增字段的名称。如果数据表有自增ID,使用 insertGetId
方法来插入记录并返回ID值
$id = DB::table('users')->insertGetId( ['email' => '[email protected]', 'votes' => 0] );
查询构造器也包含一些可以帮助你在select
语法上实现 「悲观锁定」的函数。若想在查询中实现一个「共享锁」,你可以使用sharedLock
方法。共享锁可防止选中的数据列被篡改,直到事务被提交为止 :
DB::table('users')->where('votes', '>', 100)->sharedLock()->get();另外,你也可以使用
lockForUpdate
方法。使用「更新」锁可避免行被其它共享锁修改或选取:
DB::table('users')->where('votes', '>', 100)->lockForUpdate()->get();