Dataset (query builder 19)
The query result of the database is also a data set. By default, the data set type is a two-dimensional array, but it can support returning a data set object, using the fetchCollection method:
// 获取数据集 $users = Db::name('user')->fetchCollection()->select(); // 遍历数据集 foreach($users as $user){ echo $user['name']; echo $user['id']; }
The returned data set object is think\Collection, which provides the same usage as arrays, and also encapsulates some additional methods.
When performing data set queries in the model, all data set objects are returned, but the think\model\Collection class (inherited from think\Collection) is used, but the usage is consistent.
You can directly use arrays to operate data set objects, for example:
// 获取数据集 $users = Db::name('user')->fetchCollection()->select(); // 直接操作第一个元素 $item = $users[0]; // 获取数据集记录数 $count = count($users); // 遍历数据集 foreach($users as $user){ echo $user['name']; echo $user['id']; }
The fetchCollection method also supports passing in the custom collection class name (must inherit think\Collection).
It should be noted that if you want to judge whether the data set is empty, you cannot directly use empty to judge, but must use the isEmpty method of the data set object to judge, for example:
$users = Db::name('user')->fetchCollection()->select(); if($users->isEmpty()){ echo '数据集为空'; }
Collection class contains The following main methods:
method | description |
---|---|
isEmpty | Is it empty |
toArray | Convert to array |
all | All data |
merge | Merge other data |
diff | Compare arrays and return the difference |
flip | Exchange keys and values in the data |
intersect | Compare arrays and return intersection |
keys | Return all key names in the data |
pop | Delete the last element in the data |
shift | Delete the first element in the data |
unshift | Insert an element at the beginning of the data |
push | Insert an element at the end |
reduce | By using a user-defined function, to String return array |
reverse | Data is rearranged in reverse order |
chunk | The data is separated into multiple Data block |
each | Execute callback for each element of the data |
filter | Use The callback function filters the elements in the data |
column | Returns the specified column in the data |
sort | Sort the data |
order | Specify the field to sort |
shuffle | Shuffle the data |
slice | Intercept a part of the data |
map | Use the callback function to process the elements in the array |
where | Filter elements in the array based on field conditions |
whereLike | Like query filter elements |
whereNotLike | Not Like filter element |
whereIn | IN query filter array element |
whereNotIn | Not IN element in query filter array |
whereBetween | Between query filter array The elements |
whereNotBetween | Not Between The elements in the query filter array |