Using ThinkPHP6 Collection Methods to Process Database Query Results

The article explains how ThinkPHP6 returns query results as a Collection object, introduces its useful methods such as toArray and isEmpty, and provides a PHP code example demonstrating how to check for empty results and convert the collection to an array.

php Courses
php Courses
php Courses
Using ThinkPHP6 Collection Methods to Process Database Query Results

In ThinkPHP6, after executing a database query, the returned value is a think\Collection object, which can be manipulated similarly to an array but requires specific collection methods for processing.

The most commonly used methods are toArray, which converts the collection to a plain PHP array, and isEmpty, which checks whether the collection contains any records.

Below is a code example that queries the shop_goods table, checks if the result is empty, and prints both the original collection and its array representation:

$select = Db::table('shop_goods')->whrer('id', 1)->select();
if ($select->isEmpty()) {
    echo '数据为空';
    exit;
}
print_r($select);
print_r($select->toArray());
}

When the query returns data, the output shows the collection object structure followed by the corresponding array, illustrating how the toArray method simplifies further data handling.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackenddatabasePHPTutorialCollection
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.