侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

Laravel5.1 框架数据库查询构建器用法实例详解

Laravel  /  管理员 发布于 8年前   237

本文实例讲述了Laravel5.1 框架数据库查询构建器用法。分享给大家供大家参考,具体如下:

今儿个咱说说查询构建器。它比运行原生SQL要简单些,它的操作面儿也是比较广泛的。

1 查询结果

先来看看它的语法:

  public function getSelect()  {    $result = DB::table('articles')->get();    dd($result);  }

查询构建器就是通过table方法返回的,使用get()可以返回一个结果集(array类型) 这里是返回所有的数据,当然你也可以链接很多约束。

1.1 获取一列/一行数据

  public function getSelect()  {    $result = DB::table('articles')->where('title', 'learn database')->get();  // 获取整列数据    $articles = DB::table('articles')->where('title', 'learn database')->first(); // 获取一行数据    dd($result, $articles);  }

我们可以通过where来增添条件。

1.2 获取数据列值列表

如果你想要取到某列的值的话 可以使用lists方法:

  public function getSelect()  {    $result = DB::table('articles')->where('id', '<', 2)->lists('title');    $titles = DB::table('articles')->lists('title');    dd($result, $titles);  }

1.3 获取组块儿结果集

在我们数据表中数据特别特别多时 可以使用组块结果集 就是一次获取一小块数据进行处理

  public function getSelect()  {    DB::table('articles')->chunk(2, function ($articles){      foreach ($articles as $article){        echo $article->title;        echo "
"; } }); }

如果说要终止组块运行的话 返回false就可以了:

  public function getSelect()  {    DB::table('articles')->chunk(2, function ($articles){      return false;    });  }

1.4 聚合函数

构建器还提供了很多的实用方法供我们使用:

  • count方法:返回构建器查询到的数据量。
  • max方法:传入一列 返回这一列中最大的值。
  • min方法:跟max方法类似,它返回最小的值。
  • sum方法:返回一列值相加的和。
  • avg方法:计算平均值。

1.4.1 count

  public function getArticlesInfo()  {    $article_count = DB::table('articles')->count();    dd($article_count);  }

1.4.2 max

  public function getArticlesInfo()  {    $maxCommentCount = DB::table('articles')->max('comment_count');    dd($maxCommentCount);  }

1.4.3 sum

  public function getArticlesInfo()  {    $commentSum = DB::table('articles')->sum('comment_count');  }

1.4.4 avg

  public function getArticlesInfo()  {    $commentAvg = DB::table('articles')->avg('comment_count');    dd($commentAvg);  }

1.5 select查询

1.5.1 自定义子句

select语句可以获取指定的列,并且可以自定义键:

  public function getArticlesInfo()  {    $articles = DB::table('articles')->select('title')->get();    // 输出结果://    array:3 [//      0 => {#150 //          +"title": "laravel database"//      }//      1 => {#151 //          +"title": "learn database"//       }//       2 => {#152 //          +"title": "alex"//       }//      ]    $articles1 = DB::table('articles')->select('title as articles_title')->get();    // 输出结果://    array:3 [//       0 => {#153 //          +"articles_title": "laravel database"//       }//       1 => {#154 //          +"articles_title": "learn database"//       }//       2 => {#155 //          +"articles_title": "alex"//       }//      ]    $articles2 = DB::table('articles')->select('title as articles_title', 'id as articles_id')->get();//    array:3 [//       0 => {#156 //          +"articles_title": "laravel database"//          +"articles_id": 1//       }//       1 => {#157 //          +"articles_title": "learn database"//          +"articles_id": 2//       }//       2 => {#158 //          +"articles_title": "alex"//          +"articles_id": 3//       }//      ]  }

1.5.2 distinct方法

关于distinct方法我还没弄明白到底是什么意思 适用于什么场景,也欢迎大神们给出个答案 谢谢

distinct方法允许你强制查询返回不重复的结果集。

  public function getArticlesInfo()  {    $articles = DB::table('articles')->distinct()->get();  }

1.5.3 addSelect方法

如果你想要添加一个select 可以这样做:

  public function getArticlesInfo()  {    $query = DB::table('articles')->select('title as articles_title');    $articles = $query->addSelect('id')->get();    dd($articles);  }

2 where语句

where语句是比较常用的,经常用他来进行条件筛选。

2.1 where基础介绍

现在来详细介绍下where方法 它接收三个参数:

  1. 列名,这个没什么好说的。
  2. 数据库系统支持的操作符,比如说 ”=“、”<“、”like“这些,如果不传入第二个参数 那么默认就是”=“等于。
  3. 要比较的值。
  public function getArticlesInfo()  {    $articles1 = DB::table('articles')->where('id','2')->get();     // 等于    $articles2 = DB::table('articles')->where('id','>','2')->get();   // 大于    $articles3 = DB::table('articles')->where('id','<>','2')->get();  // 不等于    $articles4 = DB::table('articles')->where('id','<=','2')->get();  // 小于等于    $articles5 = DB::table('articles')->where('title','LIKE','%base')->get();  // 类似  }

2.2 orWhere

orWhere和where接收的参数是一样的,当where逻辑没有查找到 or查找到了 返回or的结果,当where查找到了 or也查找到了 返回它们的结果。

  public function getArticlesInfo()  {    $articles = DB::table("articles")->where('id','=','5')->orWhere('title','laravel database')->get();    dd($articles);  }

2.3 whereBetween和whereNotBetween

whereBetween是指列值是否在所给定的值之间:

  public function getArticlesInfo()  {    $articles = DB::table("articles")->whereBetween('id', [1, 3])->get();    dd($articles);  }

↑ 上述代码是查找id在1~3之间的集合。

whereNotBetween和whereBetween相反:

  public function getArticlesInfo()  {    $articles = DB::table("articles")->whereNotBetween('id', [1, 3])->get();    dd($articles);  }

↑ 上述代码是查找id不在1~3之间的集合。

2.4 whereIn和whereNotIn

whereIn是查找列值在给定的一组数据中:

  public function getArticlesInfo()  {    $articles = DB::table("articles")->whereIn('id', [1, 3, 5, 8])->get();    dd($articles);  }

↑ 上述代码中是查找ID为1,3,5,8的集合,不过我们数据库中只有id为1和3的数据 那么它只会返回id为1和3的集合。

whereNotIn和whereIn相反的:

  public function getArticlesInfo()  {    $articles = DB::table("articles")->whereNotIn('id', [1, 3, 5, 8])->get();    dd($articles);  }

↑ 上述代码中是查找ID不是1,3,5,8的集合。

2.5 whereNull和whereNotNull

whereNull是查找列值为空的数据:

  public function getArticlesInfo()  {    $articles = DB::table("articles")->whereNull('created_at')->get();    dd($articles);  }

↑ 上述代码中是查找created_at为空的集合。

whereNotNull就不用说啦:

  public function getArticlesInfo()  {    $articles = DB::table("articles")->whereNotNull('created_at')->get();    dd($articles);  }

↑ 上述代码中是查找created_at不为空的集合。

3 插入数据

先看下最简单的插入方法:

  public function getInsertArticle()  {    // 插入一条数据:    DB::table('articles')->insert(      ['title'=>'get more', 'body'=>'emmmmmm......']    );    // 插入多条数据:    DB::table('articles')->insert([      ['title'=>'testTitle1', 'body'=>'testBody1'],      ['title'=>'testTitle2', 'body'=>'testBody2'],      // ....    ]);  }

当你需要拿到插入数据的ID的话,可以使用获取自增ID的方法:

  public function getInsertArticle()  {    // 插入一条数据:    $id = DB::table('articles')->insertGetId(      ['title'=>'get more', 'body'=>'emmmmmm......']    );    dd($id);  }

4 更新

  public function getUpdateArticle()  {    $result = DB::table('articles')->whereBetween('id', [1, 3])->update(['comment_count'=>0]);    dd($result);  }

↑ update还可以返回影响了几条数据。

4.1 加/减快捷方法

  public function getUpdateArticle()  {    $result = DB::table('articles')->whereBetween('id', [1, 3])->increment('comment_count',2);    dd($result);  }

↑ increment接受1~2个参数,第一个参数是列名,第二个参数是可选的表示增加几(默认是1),上面的语句是:comment_count这一列的值增加2。

  public function getUpdateArticle()  {    $result = DB::table('articles')->whereBetween('id', [1, 3])->decrement('comment_count',2);    dd($result);  }

↑ decrement接受1~2个参数,第一个参数是列名,第二个参数是可选的表示减少几(默认是1),上面的语句是:comment_count这一列的值减少2。

你以为加减快捷方法只接收两个参数么?nonono 它还可以接收第三个参数:

  public function getUpdateArticle()  {    $result = DB::table('articles')->whereBetween('id', [1, 3])->increment('comment_count', 2, ['title' => 'testUpdate']);    dd($result);  }

↑ 它还可以在增加/减少时对其他列进行修改。

5 删除

  public function getDeleteArticle()  {    $result = DB::table('articles')->whereBetween('id', [1, 3])->delete();    dd($result);  }

↑ 用delete删除数据,它也返回有多少行被影响。

当你想要删除所有的列 并且把自增ID归0的话 可以这么做:

  public function getDeleteArticle()  {    DB::table('articles')->truncate();  }

6 锁

查询构建器还包含一些方法帮助你在select语句中实现”悲观锁“。可以在查询中使用sharedLock方法从而在运行语句时带一把”共享锁“。共享锁可以避免被选择的行被修改直到事务提交:

DB::table('articles')->where('id', '>', 100)->sharedLock()->get();

此外你还可以使用lockForUpdate方法。”for update“锁避免选择行被其它共享锁修改或删除:

DB::table('articles')->where('id', '>', 100)->lockForUpdate()->get();

更多关于Laravel相关内容感兴趣的读者可查看本站专题:《Laravel框架入门与进阶教程》、《php优秀开发框架总结》、《php面向对象程序设计入门教程》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》

希望本文所述对大家基于Laravel框架的PHP程序设计有所帮助。

您可能感兴趣的文章:

  • laravel框架数据库操作、查询构建器、Eloquent ORM操作实例分析
  • laravel通用化的CURD的实现
  • Laravel框架查询构造器 CURD操作示例
  • Laravel框架实现model层的增删改查(CURD)操作示例
  • Laravel框架数据库CURD操作、连贯操作总结
  • laravel5.6 框架操作数据 Eloquent ORM用法示例
  • laravel 操作数据库常用函数的返回值方法
  • laravel框架数据库配置及操作数据库示例
  • laravel5.6框架操作数据curd写法(查询构建器)实例分析


  • 上一条:
    Laravel5.1 框架模型创建与使用方法实例分析
    下一条:
    Laravel5.1 框架数据库操作DB运行原生SQL的方法分析
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • Laravel 11.15版本发布 - Eloquent Builder中添加的泛型(0个评论)
    • Laravel 11.14版本发布 - 新的字符串助手和ServeCommand改进(0个评论)
    • Laravel 11.12版本发布 - Artisan的`make`命令自动剪切`.php `扩展(0个评论)
    • Laravel的轻量型购物车扩展包:binafy/laravel-cart(0个评论)
    • Laravel 11.11版本发布 - 查看模型中的第三方关系:show(0个评论)
    • 近期文章
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • PHP 8.4 Alpha 1现已发布!(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2017-07
    • 2017-08
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2020-07
    • 2020-08
    • 2020-09
    • 2020-10
    • 2020-11
    • 2021-01
    • 2021-02
    • 2021-03
    • 2021-04
    • 2021-05
    • 2021-06
    • 2021-07
    • 2021-08
    • 2021-09
    • 2021-10
    • 2021-11
    • 2021-12
    • 2022-01
    • 2022-02
    • 2022-03
    • 2022-04
    • 2022-05
    • 2022-06
    • 2022-07
    • 2022-08
    • 2022-09
    • 2022-10
    • 2022-11
    • 2022-12
    • 2023-01
    • 2023-02
    • 2023-03
    • 2023-04
    • 2023-05
    • 2023-06
    • 2023-07
    • 2023-08
    • 2023-09
    • 2023-10
    • 2023-11
    • 2023-12
    • 2024-01
    • 2024-02
    • 2024-03
    • 2024-04
    • 2024-05
    • 2024-06
    • 2024-07
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客