laravel学习

来源:互联网 发布:免费vpn软件下载 编辑:程序博客网 时间:2024/06/14 03:03

查询构建器

[ Laravel 5.4 文档 ] 数据库 —— 查询构建器
1. 获取结果集

从一张表中取出所有行$users = DB::table('users')->get();从一张表中获取一行/一列$user = DB::table('users')->where('name', 'John')->first();$email = DB::table('users')->where('name', 'John')->value('email');//返回指定的值获取数据列值列表$titles = DB::table('roles')->pluck('title');//获取角色标题数组$roles = DB::table('roles')->pluck('title', 'name');//返回数组中为列值指定自定义键组块结果集DB::table('users')->orderBy('id')->chunk(100, function($users) {    foreach ($users as $user) {        //users 表数据分割成一次处理 100 条记录的小组块        //return false;//从闭包函数中返回 false 来终止组块的运行    }});聚合函数//多个聚合方法,如 count,max,min,avg和sum,可在构造查询之后调用这些方法$users = DB::table('users')->count();$price = DB::table('orders')->max('price');//可联合其它查询子句和聚合函数来构建查询$price = DB::table('orders')->where('finalized', 1)->avg('price');
  1. 查询
指定查询子句$users = DB::table('users')->select('name', 'email as user_email')->get();$users = DB::table('users')->distinct()->get();//distinct 强制查询返回不重复的结果集$query = DB::table('users')->select('name');$users = $query->addSelect('age')->get();//addSelect 已有查询构建器实例并且希望添加一个查询列到已存在的 select 子句
  1. 原生表达式
//DB::raw方法,创建一个原生表达式$users = DB::table('users')         ->select(DB::raw('count(*) as user_count, status'))         ->where('status', '<>', 1)         ->groupBy('status')         ->get();
  1. 连接(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();//单个查询中连接多张表左连接$users = DB::table('users')         ->leftJoin('posts', 'users.id', '=', 'posts.user_id')         ->get();交叉连接$users = DB::table('sizes')         ->crossJoin('colours')         ->get();高级连接语句DB::table('users')    ->join('contacts', function ($join) {        $join->on('users.id', '=', 'contacts.user_id')->orOn(...);    })    ->get();//在查询中使用 where 和orWhere 方法DB::table('users')    ->join('contacts', function ($join) {        $join->on('users.id', '=', 'contacts.user_id')             ->where('contacts.user_id', '>', 5);    })    ->get();
  1. 联合(Union)
//先创建一个查询,然后使用 union 方法将其和第二个查询进行联合$first = DB::table('users')->whereNull('first_name');$users = DB::table('users')->whereNull('last_name')->union($first)->get();

注:unionAll 方法也是有效的,并且和 union 有同样的使用方式。

  1. Where子句
简单where查询$users = DB::table('users')->where('votes', 100)->get();//操作符来编写where 子句$users = DB::table('users')->where('votes', '=', 100)->get();$users = DB::table('users')->where('votes', '>=', 100)->get();$users = DB::table('users')->where('votes', '<>', 100)->get();$users = DB::table('users')->where('name', 'like', 'T%')->get();//传递条件数组到 where 函数$users = DB::table('users')->where([    ['status', '=', '1'],    ['subscribed', '<>', '1'],])->get();or语句$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 方法验证给定列的值是否在给定数组中:$users = DB::table('users')->whereIn('id', [1, 2, 3])->get();//whereNotIn 方法验证给定列的值不在给定数组中:$users = DB::table('users')->whereNotIn('id', [1, 2, 3])->get();//whereNull 方法验证给定列的值为NULL:$users = DB::table('users')->whereNull('updated_at')->get();//whereNotNull 方法验证给定列的值不是 NULL:$users = DB::table('users')->whereNotNull('updated_at')->get();//whereDate 方法用于比较字段值和日期:$users = DB::table('users')->whereDate('created_at', '2016-10-10')->get();//whereMonth 方法用于比较字段值和一年中的指定月份:$users = DB::table('users')->whereMonth('created_at', '10')->get();//whereDay 方法用于比较字段值和一月中的制定天:$users = DB::table('users')->whereDay('created_at', '10')->get();//whereYear 方法用于比较字段值和指定年:$users = DB::table('users')->whereYear('created_at', '2016')->get();//whereColumn 方法用于验证两个字段是否相等:$users = DB::table('users')->whereColumn('first_name', 'last_name')->get();    可传递一个比较运算符到该方法$users = DB::table('users')->whereColumn('updated_at', '>', 'created_at')->get();    可传递多条件数组到 whereColumn 方法,这些条件通过 and 操作符进行连接:$users = DB::table('users')         ->whereColumn([            ['first_name', '=', 'last_name'],            ['updated_at', '>', 'created_at']         ])->get();参数分组DB::table('users')        ->where('name', '=', 'John')        ->orWhere(function ($query) {            $query->where('votes', '>', 100)                  ->where('title', '<>', 'Admin');        })        ->get();//上述语句等价于下面的 SQLselect * from users where name = 'John' or (votes > 100 and title <> 'Admin')//where exists子句DB::table('users')    ->whereExists(function ($query) {        $query->select(DB::raw(1))              ->from('orders')              ->whereRaw('orders.user_id = users.id');    })    ->get();//上述语句等价于下面的 SQLselect * from userswhere exists (    select 1 from orders where orders.user_id = users.id)JSON Where子句//使用操作符 -> 查询 JSON 字段类型$users = DB::table('users')->where('options->language', 'en')->get();$users = DB::table('users')->where('preferences->dining->meal', 'salad')->get();
  1. 排序、分组、限定
orderBy 方法给定字段对结果集进行排序——asc或desc$users = DB::table('users')->orderBy('name', 'desc')->get();latest 和 oldest 方法日期对结果进行排序,默认情况下通过 created_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();havingRaw 方法可用于设置原生字符串作为 having 子句的值,例如,可找到所有售价大于 2500 的部分$users = DB::table('orders')            ->select('department', DB::raw('SUM(price) as total_sales'))            ->groupBy('department')            ->havingRaw('SUM(price) > 2500')            ->get();skip 和 take 方法限定查询返回的结果集的数目,或者在查询中跳过给定数目的结果$users = DB::table('users')->skip(10)->take(5)->get();作为替代方法,还可以使用 limit 和offset 方法:$users = DB::table('users')->offset(10)->limit(5)->get();
  1. 条件子句
when 方法在参数1true 时才执行给定闭包,如参数1false,则闭包不执行$role = $request->input('role');$users = DB::table('users')         ->when($role, function ($query) use ($role) {            return $query->where('role_id', $role);         })         ->get();when方法可传递另一个闭包作为的参数3,该闭包会在参数1false的情况下执行:$sortBy = null;$users = DB::table('users')         ->when($sortBy, function ($query) use ($sortBy) {                return $query->orderBy($sortBy);            }, function ($query) {                return $query->orderBy('name');            })         ->get();
  1. 插入(Insert)
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]]);insertGetId 方法来插入记录并返回ID值:$id = DB::table('users')->insertGetId(    ['email' => 'john@example.com', 'votes' => 0]);

注:当使用 PostgresSQL 时insertGetId 方法默认自增列被命名为 id,如果你想要从其他“序列”获取ID,可以将序列名作为第二个参数传递到insertGetId 方法。

  1. 更新(Update)
DB::table('users')->where('id', 1)->update(['votes' => 1]);//更新JSON字段DB::table('users')->where('id', 1)->update(['options->enabled' => true]);增加/减少//参数1需要修改的列。参数2可选,用于控制列值增加/减少的数目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, ['name' => 'John']);
  1. 删除(Delete)
DB::table('users')->delete();DB::table('users')->where('votes', '>', 100)->delete();清除整张表,并将自增ID置为0,可使用 truncate 方法DB::table('users')->truncate();
  1. 悲观锁
在查询中使用 sharedLock 方法在运行语句时带一把”共享锁“。共享锁可避免被选择的行被修改直到事务提交DB::table('users')->where('votes', '>', 100)->sharedLock()->get();使用 lockForUpdate 方法。“for update”锁避免选择行被其它共享锁修改或删除:DB::table('users')->where('votes', '>', 100)->lockForUpdate()->get();

常用命令

php artisan cache:clear #清除缓存php artisan make:model Active #建立模型php artisan make:Controller ActiveController #建立控制器php artisan migrate:refresh #刷新php artisan migrate #建立数据库

获得各个根文件夹路径

APP目录: app_path();config目录:  config_path();public目录:  public_path();storage目录: storage_path();
原创粉丝点击