DB门面-数据查询

1.1.1 查询所有数据
$selData = DB::table('article')->get();
1.1.2 单条件查询
#DB::table('表名')->where('字段','表达式','数据')->get();
$selData = DB::table('article')->where('id','=',10)->get();
1.1.3 多条件查询
#DB::table('表名')->where([[条件1],[条件2],[条件3]])->get();
$selData = DB::table('article')->where([['a_id','<',10],['a_title','like','%a%']])->get();
1.1.4 between区间查询+orderBy排序
#DB::table('表名')->whereBetween('字段',[起始范围,终止范围])->orderBy('字段','排序方式')->get();
$selData = DB::table('article')->whereBetween('a_id',[20,30])->orderBy('a_id','desc')->get();
1.1.5 orderBy排序+limit查询
#DB::table('表名')->orderBy('排序的字段','排序方式')->limit(条数)->get();
DB::table('article')->orderBy('a_id','desc')->limit(1)->get();
1.1.6 in和not in查询
#DB::table('表名')->whereIn('字段',[结果范围])->get();
DB::table('users')->whereIn('id', [1, 2, 3])->get();

#DB::table('表名')->whereNotIn('字段',[结果范围])->get();
DB::table('users')->whereNotIn('id', [1, 2, 3])->get();

1.1.7 连接查询
#DB::table('主表名')->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();

#DB::table('主表名')->leftJoin('副表名','主表.关联字段','表达式','副表.关联字段')
$users = DB::table('users')
            ->leftJoin('posts', 'users.id', '=', 'posts.user_id')
            ->get();

#DB::table('主表名')->rightJoin('副表名','主表.关联字段','表达式','副表.关联字段')
$users = DB::table('users')
            ->rightJoin('posts', 'users.id', '=', 'posts.user_id')
            ->get();

1.1.8 子查询
#有时你可能需要构造一个 where 语句,将子查询的结果与一个给定值进行比较。这你可以通过给 where 方法传递一个闭包以及给定值实现。
#举例来说,下面的查询语句将会获取到所有属于最近一个会员类型的所有用户。
#whereColumn用于比较两个字段的值是否相等
$users = User::where(function ($query) {
    $query->select('type')
        ->from('membership')
        ->whereColumn('user_id', 'users.id')
        ->orderByDesc('start_date')
        ->limit(1);
}, 'Pro')->get();
1.1.9 分组查询
#根据账户ID进行分组.并对分组之后的数据进行筛选,id大于100的数据
$users = DB::table('users')
            ->groupBy('account_id')
            ->having('account_id', '>', 100)
            ->get();

1.1.1 聚合函数
#统计总用户量
$users = DB::table('users')->count();

#找出订单中价格最高的记录
$price = DB::table('orders')->max('price');

#查询以支付成功的订单平均价钱
$price = DB::table('orders')
            ->where('finalized', 1)
            ->avg('price');
更多查询方案
first取一条数据
find根据ID取一条数据
value从记录中获取单个值
pluck获取一列的值
select指定字段查询
orWhere或者
inRandomOrder方法被用来将结果随机排序
latest/oldest方法可以使你轻松地通过日期排序
whereColumn用于比较两个字段的值是否相等

 

posted @ 2021-12-14 09:59  王越666  阅读(34)  评论(0编辑  收藏  举报