| 版本 | 功能調整 |
| --- | --- |
| 5.0.5 | 原生查詢不支持返回數據集對象 |
默認的結果類型是數組
```
'resultset_type' => 'array',
```
### **獲取單條數據**
Db類find返回數組
```
$users = \think\Db::name('user')->find(1);
```

返回Model模型對象(這里是User模型對象)
模型對象數據庫查出的值在data屬性里,
通過__get動態獲取字段的值
```
$users1 = model('user')->find(1);
$users2 = model('user')::find(1);
$users3 = model('user')::get(1);
echo $users1->id;
echo $users2->id;
echo $users3->id;
```

模型對象可以直接使用toArray()轉成數組
```
$user1=$users1->toArray()
```

### **獲取多條數據**
select和All默認返回模型組成的數組
```
$users1 = \think\Db::name('user')->select();
$users2 = model('user')::all();
$users3 = \app\index\model\User::all();
```

可知select和All在` 'resultset_type' => 'array',`的情況下是無法直接使用toArray的
我們可以將User模型遍歷出來在進行toArray()進行轉化,第二種辦法就是直接將數據轉為數據集類在進行toArray()
```
collection($users3)->toArray()
```

### **讓select和All默認返回數據集類**
數據庫的查詢結果也就是數據集,database.php默認的配置下,數據集的類型是一個二維數組,我們可以配置成數據集類,就可以支持對數據集更多的對象化操作,需要使用數據集類功能,可以有以下幾種方法
**1、database.php配置數據庫的`resultset_type`參數如下:**
~~~
return [
// 數據集返回類型 注意這里的值是全小寫的collection,或者`'\think\Collection'`
'resultset_type' => 'collection',
];
~~~
**2、或者在模型中定義resultSetType 屬性**
~~~
protected $resultSetType = 'collection';
~~~
**3、V5.1.23+ 版本開始,你可以在查詢的時候指定是否需要返回數據集(無需配置 resultset\_type 參數)**
~~~
// 獲取數據集
$users = Db::name('user')->fetchCollection()->select();
~~~
配置完成后返回的數據集對象是`think\Collection`,
```
$users1 = \think\Db::name('user')->select();
$users2 = model('user')::all();
$users3 = \app\index\model\User::all();
```

`think\Collection`提供了和數組無差別用法,并且另外封裝了一些額外的方法。、
可以直接使用數組的方式操作數據集對象,例如:
~~~
// 獲取數據集
$users = \think\Db::name('user')->select();
// 直接操作第一個元素結果直接為數組了哦
$item = $users[0];
dump($item);
// 獲取數據集記錄數
$count = count($users);//3
// 遍歷數據集
foreach($users as $user){
//遍歷后的$user也是數組了
echo $user['username'].'<--->';
echo $user['id'].'@<br>';
}
//數據集直接轉為數組
$users_arr=$users->toArray();
dump($users_arr);
~~~

需要注意的是,如果要判斷數據集是否為空,不能直接使用`empty`判斷,而必須使用數據集對象的`isEmpty`方法判斷,例如:
~~~
$users = \think\Db::name('user')->select();
if($users->isEmpty()){
echo '數據集為空';
}
~~~
## **總結:**
>[info]find() 查詢結果必為 一維數組
value/column 查詢結果必為 int/string/一維數組
select與All 當配置resultset\_type => collection 時, 查詢結果為 collection數據集
select 當配置resultset\_type => array時,如果用Db::類查詢為二維數組,但如果用Model類查詢為Model對象(使用不當會報錯,因為它是個對象)可用collection($Model);轉為數據集
結論:
Query查詢單條數據返回數組,Model查詢單條數據返回的模型類可以直接使用toArray()轉數組
Query和Model查詢多條數據時
## **數據集方法操作**
**Model:**
```
// 獲取數據集
$users = model('user')->select();
if ($users instanceof \think\Collection && !$users->isEmpty()) {
//獲取全部的數據
dump($users->all());
dump($users->toArray());
}
```

雖然返回的是Model但是還是可以向操作數組那樣操作Model里的data屬性
```
// 獲取數據集
$users = model('user')->select();
$users = model('user')::All();
if ($users instanceof \think\Collection && !$users->isEmpty()) {
//獲取全部的數據
dump($users);
dump($users->all());
dump($users->column('id','username'));//column用法和array_column一致
dump($users[0]['username']);
$users[0]['xixi']='haha';
dump($users->toArray());
}
```


**Query:**
```
// 獲取數據集
$users = \think\Db::name('user')->select();
if ($users instanceof \think\Collection && !$users->isEmpty()) {
//獲取全部的數據 Query獲取多條數據時,同$users->toArray()
dump($users->all());
$newUsers=$users->merge(['name'=>'dash']);
dump($newUsers);
$newUsers=$users->merge([['name'=>'dash','id'=>4,'pwd'=>'123','sex'=>'1']]);
dump($newUsers);
dump($users->all());
dump($newUsers->all());
}
```

```
// 獲取數據集
$users = \think\Db::name('user')->select();
if ($users instanceof \think\Collection && !$users->isEmpty()) {
//獲取全部的數據
dump($users->all());
$users->pop();
dump($users->all());
}
```

```
// 獲取數據集
$users = \think\Db::name('user')->select();
if ($users instanceof \think\Collection && !$users->isEmpty()) {
//獲取全部的數據
dump($users->all());
$users->unshift(['name'=>'張三','id'=>4,'pwd'=>'123','sex'=>'1']);
$users->unshift(['name'=>'李四','id'=>5,'pwd'=>'456','sex'=>'1'],"自定義鍵");
dump($users->all());
}
```

```
// 獲取數據集
$users = \think\Db::name('user')->select();
if ($users instanceof \think\Collection && !$users->isEmpty()) {
//獲取全部的數據
dump($users->all());
dump($users->column('id'));//column用法和array_column一致
dump($users->column('id','username'));
}
```

`Collection`類包含了下列主要方法:
| 方法 | 描述 |
| --- | --- |
| isEmpty() | 是否為空 |
| toArray() | 轉換為數組 |
| toJson() | 轉換為json |
| all() | 所有數據 |
| merge($items) | 合并其它數據 |
| diff($items) | 比較數組,返回差集 |
| flip() | 交換數據中的鍵和值 |
| intersect($items) | 比較數組,返回交集 |
| keys() | 返回數據中的所有鍵名 |
| pop() | 刪除數據中的最后一個元素 |
| shift() | 刪除數據中的第一個元素 |
| unshift($value, $key = null) | 在數據開頭插入一個元素 |
| push($value, $key = null)| 在數組結尾插入一個元素 |
| reduce(callable $callback, $initial = null) | 通過使用用戶自定義函數,以字符串返回數組 |
| reverse() | 數據倒序重排 |
| chunk($size, $preserveKeys = false) | 數據分隔為多個數據塊 |
| each(callable $callback) | 給數據的每個元素執行回調 |
| filter(callable $callback = null) | 用回調函數過濾數據中的元素 |
| column($columnKey, $indexKey = null) | 返回數據中的指定列 |
| sort(callable $callback = null) | 對數據排序 |
| shuffle() | 將數據打亂 |
| slice($offset, $length = null, $preserveKeys = false) | 截取數據中的一部分 |
- 目錄結構與基礎
- 修改數據后頁面無變化
- 防跨目錄設置
- input
- 系統目錄
- 自動生成的文件以及目錄
- 類自動加載
- url生成
- 數據增刪改查
- 增加數據
- 數據更新
- 數據刪除
- 數據查詢
- 架構
- 生命周期
- 入口文件
- URL訪問規則
- 配置
- 默認慣例配置配置
- 初始應用配置
- 路由
- 域名路由
- URL生成
- 數據庫操作
- 方法列表
- 連接數據庫
- 分布式數據庫
- 查詢構造器
- 查詢數據
- 添加數據
- 更新數據
- 刪除數據
- 查詢語法
- 聚合查詢(統計)
- 時間查詢
- 高級查詢
- 視圖查詢
- 子查詢
- 輔助查詢之鏈式操作
- where
- table
- alias
- field
- order
- limit
- page
- group
- having
- join
- union
- distinct
- lock
- cache
- comment
- fetchSql
- force
- bind
- partition
- strict
- failException
- sequence(pgsql專用)
- 查詢事件
- 事務操作
- 監聽SQL
- 存儲過程
- 數據集
- 控制器
- 跳轉和重定向
- 空控制器和空操作
- 分層控制器
- Rest控制器
- 資源控制器
- 自動定位控制器
- tp3的增刪改查
- 方法注入
- 模型
- 屬性方法一覽
- 類方法詳解
- Model
- 調用model不存在的屬性
- 調用model中不存在的方法
- 調用model中不存在的靜態方法
- hasOne
- belongsTo
- hasMany {Relation}
- belongsToMany
- hasManyThrough
- morphMany
- morphOne
- morphTo
- ::hasWhere {Query}
- ::has
- relationCount
- data 【model】
- setInc {integer|true}
- setDec {integer|true}
- save {integer | false}
- saveAll {array}
- delete {integer}
- ::get 查詢單條數據 {Model}
- ::all 查詢多條數據{Model [ ]}
- ::create 新增單條數據 {Model}
- ::update 更新單條數據 {Model}
- ::destroy {integer}
- ::scope {Query}
- getAttr {mixed}
- xxx
- append
- appendRelationAttr
- hidden
- visible
- except
- readonly
- auto
- together
- allowField
- isUpdate
- validate
- toCollection
- toJson
- toArray
- 定義
- 新增
- 更新
- 查詢
- 刪除
- 聚合
- 獲取器
- 修改器
- 時間戳
- 只讀字段
- 軟刪除
- 類型轉換
- 數據完成
- 查詢范圍
- 模型分層
- 數組訪問和轉換
- JSON序列化
- 事件
- 關聯
- 一對一關聯
- 主表一對一關聯
- 從表一對一關聯(相對關聯)
- 一對多關聯
- 主表定義一對多關聯
- 從表定義一對多關聯
- 遠程一對多
- 多對多關聯
- 多態關聯
- 動態屬性
- 關聯預載入with()
- 關聯統計
- N+1查詢
- 聚合模型
- Model方法集合
- 表單驗證
- 驗證器
- 驗證規則
- 錯誤信息
- 驗證場景
- 控制器驗證
- 模型驗證
- 內置規則
- 靜態調用
- 表單令牌
- Token身份令牌
- 視圖
- 模版
- 變量輸出
- 函數輸出
- Request請求參數
- 模板注釋及原樣輸出
- 三元運算
- 內置標簽
- 模板繼承
- 模板布局
- 日志
- 日志初始化
- 日志驅動
- 日志寫入
- 獨立日志
- 日志清空
- 寫入授權
- 自定義日志
- 錯誤和調試
- 異常
- php系統異常及thinkphp5異常機制
- 異常處理
- 拋出異常
- 異常封裝
- resful
- 404頁面
- 調試模式
- Trace調試
- SQL調試
- 變量調試
- 性能調試
- 遠程調試
- 安全
- 輸入安全
- 數據庫安全
- 上傳安全
- 其它安全建議
- xss過濾
- 擴展
- 函數
- 類庫
- 行為
- 驅動
- Composer包
- Time
- 數據庫遷移工具
- Workerman
- MongoDb
- htmlpurifier XSS過濾
- 新浪SAE
- oauth2.0
- 命令行及生成文件
- 系統現成命令
- 創建類庫文件
- 生成類庫映射文件
- 生成路由緩存
- 清除緩存文件
- 生成配置緩存文件
- 生成數據表字段緩存
- 自定義命令行
- 開始
- 調用命令
- 雜項
- 助手函數
- URL重寫
- 緩存
- 緩存總結
- Session
- Cookie
- 多語言
- 分頁
- 上傳
- 驗證碼
- 圖像處理
- 文件處理
- 單元測試
- 自定義表單令牌