mirror of
https://gitee.com/hyperf/hyperf.git
synced 2024-12-05 05:07:58 +08:00
Added select.md
This commit is contained in:
parent
c77465cf2e
commit
6582ee322b
@ -13,7 +13,7 @@ Hyperf 是基于Swoole4.2+的高性能、高灵活性的PHP框架。内置协程
|
||||
## 模型
|
||||
|
||||
- 快速开始: [介绍](zh/model/intro.md) | [配置](zh/model/config.md)
|
||||
- 查询构造器:
|
||||
- 查询构造器: [查询](zh/model/select.md)
|
||||
- 模型事件:
|
||||
- 模型关系:
|
||||
|
||||
|
43
zh/model/select.md
Normal file
43
zh/model/select.md
Normal file
@ -0,0 +1,43 @@
|
||||
# 数据库查询
|
||||
|
||||
这里只提供一部分常用的教程,具体教程可以到Laravel官网查看。
|
||||
[Laravel Query Builder](https://laravel.com/docs/5.8/queries)
|
||||
|
||||
## 使用DB助手类
|
||||
|
||||
~~~php
|
||||
use Hyperf\DbConnection\Db;
|
||||
|
||||
$users = Db::select('SELECT * FROM user;');
|
||||
$users = Db::table('user')->get();
|
||||
$users = Db::table('user')->select('name', 'sex as user_sex')->get();
|
||||
~~~
|
||||
|
||||
`Db::select()`方法会返回一个array,而`get`方法会返回`Illuminate\Support\Collection`。其中元素是`stdClass`,所以可以通过以下代码返回各个元素的数据
|
||||
|
||||
~~~php
|
||||
<?php
|
||||
|
||||
foreach ($users as $user) {
|
||||
echo $user->name;
|
||||
}
|
||||
~~~
|
||||
|
||||
框架还提供了聚合类方法,例如`count`, `max`, `min`, `avg`, `sum`。
|
||||
|
||||
~~~php
|
||||
use Hyperf\DbConnection\Db;
|
||||
|
||||
$count = Db::table('user')->count();
|
||||
~~~
|
||||
|
||||
## 原始表达式
|
||||
|
||||
有时你需要在查询中使用原始表达式,例如实现`COUNT(0) AS count`,这就需要用到`raw`方法。
|
||||
|
||||
~~~php
|
||||
use Hyperf\DbConnection\Db;
|
||||
|
||||
$res = Db::table('user')->select('sex', Db::raw('COUNT(0) AS `count`'))->groupBy('sex')->get();
|
||||
~~~
|
||||
|
@ -1,3 +1,5 @@
|
||||
- 快速开始
|
||||
- [介绍](zh/model/intro.md)
|
||||
- [配置](zh/model/config.md)
|
||||
- [配置](zh/model/config.md)
|
||||
- 查询构造器
|
||||
- [查询](zh/model/select.md)
|
Loading…
Reference in New Issue
Block a user