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:

methoddescription
isEmptyIs it empty
toArrayConvert to array
allAll data
mergeMerge other data
diffCompare arrays and return the difference
flipExchange keys and values ​​in the data
intersectCompare arrays and return intersection
keysReturn all key names in the data
popDelete the last element in the data
shiftDelete the first element in the data
unshiftInsert an element at the beginning of the data
pushInsert an element at the end
reduceBy using a user-defined function, to String return array
reverseData is rearranged in reverse order
chunkThe data is separated into multiple Data block
eachExecute callback for each element of the data
filterUse The callback function filters the elements in the data
columnReturns the specified column in the data
sortSort the data
orderSpecify the field to sort
shuffleShuffle the data
sliceIntercept a part of the data
mapUse the callback function to process the elements in the array
whereFilter elements in the array based on field conditions
whereLikeLike query filter elements
whereNotLikeNot Like filter element
whereInIN query filter array element
whereNotInNot IN element in query filter array
whereBetweenBetween query filter array The elements
whereNotBetweenNot Between The elements in the query filter array