Data retrieval is a fundamental operation in ThinkPHP development. This article systematically explains how to efficiently and flexibly fetch data using three main methods: database queries, model queries, and the query builder.
ThinkPHP supports executing native SQL statements to query the database, suitable for complex or specific SQL operations. Here's an example:
// Query the database using native SQL
$sql = "SELECT * FROM users";
$result = Db::query($sql);
foreach ($result as $row) {
// Process the query result
}
In the example above, Db::query() executes the SQL statement and returns an array, making it easy to iterate over each record.
You can filter data flexibly using the WHERE clause in SQL. Here's an example:
// Query with conditions using native SQL
$sql = "SELECT * FROM users WHERE age > 18";
$result = Db::query($sql);
foreach ($result as $row) {
// Process the query result
}
This query returns only user information where age is greater than 18.
ThinkPHP models provide an object-oriented encapsulation of database tables, simplifying database operations. Example:
// Query database using a model
$users = new UsersModel();
$result = $users->where('age', '>', 18)->select();
foreach ($result as $row) {
// Process the query result
}
Create an instance of the model, use where() to set conditions, then execute the query with select(). The result is a data collection.
The query builder allows chaining methods to build queries more intuitively and succinctly. Example:
// Query database using the query builder
$result = Db::table('users')->where('age', '>', 18)->select();
foreach ($result as $row) {
// Process the query result
}
Specify the table with table(), set conditions with where(), and execute the query using select(). This approach is flexible and convenient.
This article introduced three common ways to retrieve data in ThinkPHP: native database queries, model queries, and the query builder. Each method has its advantages, and developers can choose the most suitable one according to their needs to perform data retrieval. Mastering these techniques greatly enhances ThinkPHP development efficiency.
In daily development, using appropriate query methods improves code maintainability and performance. We hope this article helps you with your ThinkPHP projects.