Data query in Yii framework: access data efficiently
Jun 21, 2023 am 11:22 AMYii framework is an open source PHP web application framework that provides numerous tools and components to simplify the process of web application development, of which data query is one of the important components. In the Yii framework, we can use SQL-like syntax to access the database to query and manipulate data efficiently.
The query builder of Yii framework mainly includes the following types: Active Record query, Query Builder query, command query and original SQL query. This article will introduce these query builders and how to use them one by one to help beginners better master how to use data queries in the Yii framework.
- Active Record Query
Active Record mode is one of the most commonly used data access modes in the Yii framework. It provides an object-oriented interface that allows us to Manipulate data in the database just as you would an object-oriented instance. In the Yii framework, each Active Record class corresponds to a database table, and we can access the data in the table by calling the static method of the class.
The following is an example of an Active Record query:
//創(chuàng)建一個Active Record對象 $post = Post::findOne(1); //輸出該對象的屬性 echo $post->title;
In this example, we first create a Post
class using the findOne()
method Instance of Attributes. In actual development, we usually need to perform data filtering, sorting, paging and other operations. The Yii framework provides rich methods to implement these functions. For example, we can use the
where()
method to add filter conditions, the
method to specify the sorting method, and the limit()
method to limit returns The number of records, use the offset()
method to specify the starting position of the returned record. The following is an example: <pre class='brush:php;toolbar:false;'>//查詢標題包含“Yii”并且作者為“admin”的文章,并按照發(fā)布時間倒序排序,返回前10條記錄
$posts = Post::find()->where(['like', 'title', 'Yii'])
->andWhere(['author' => 'admin'])
->orderBy(['created_at' => SORT_DESC])
->limit(10)
->offset(0)
->all();</pre>
In this example, we use the find()
method to create an Active Record query object, and then use
and # The ##andWhere() method adds two filter conditions, namely that the title contains "Yii" and the author is "admin"; the
orderBy() method is used to specify sorting in reverse order of release time; use The
limit() method limits the number of returned records to 10; use the
offset() method to specify that the starting position of the returned records is 0 records. Finally, we use the
all() method to execute the query and return all records that meet the requirements.
Query BuilderQuery
- Yii::$app->db->createCommand()
- method to create a Query Builder object, and then use a series of methods of the object to build query statements.
//創(chuàng)建一個查詢構建器對象,并構建查詢語句 $query = Yii::$app->db->createCommand() ->select('id, title, content') ->from('post') ->where(['like', 'title', 'Yii']) ->andWhere(['author' => 'admin']) ->orderBy(['created_at' => SORT_DESC]) ->limit(10) ->offset(0); //執(zhí)行查詢,并返回結果集 $posts = $query->queryAll();
In this example, we first use
Yii::$app->db->createCommand() The method creates a Query Builder object and then uses the object's select()
,from(),
where(),
andWhere()# Methods such as ##, orderBy()
, limit()
, and offset()
are used to construct query statements. Finally, we use the queryAll()
method to execute the query and return all records that meet the requirements. The biggest difference between Query Builder and Active Record is that Query Builder does not need to define a model class, so it is suitable for some simple query scenarios, such as statistical queries.
Command query
Command query is the most original data access method in the Yii framework. We can use this method to perform some database operations that do not require returning a result set. Such as update, delete, insert, etc. In the Yii framework, we can use the
Yii::$app->db->createCommand()- method to create a Command object, and then use the
- execute() method of the object to execute SQL statements.
The following is an example of a command query: <pre class='brush:php;toolbar:false;'>//創(chuàng)建一個命令對象,并執(zhí)行SQL語句
Yii::$app->db->createCommand()
->update('post', ['status' => 1], 'author = "admin"')
->execute();</pre>
In this example, we first use the Yii::$app->db->createCommand()
method Created a Command object, and then used the object's
method to construct an update statement that changed all
author in the post
table to "admin "The status attribute of the record is updated to 1; finally, we use the execute()
method to execute the update statement. Original SQL query
In some special cases, we may need to execute some complex query statements that cannot be processed through Active Record, Query Builder or command query. Raw SQL queries can be used at this time. In the Yii framework, we can use the
- method to create a Command object, and then use the
- setSql() method of the object To specify the original SQL statement, and use the
method to execute the query. The following is an example of a raw SQL query:
<pre class='brush:php;toolbar:false;'>//創(chuàng)建一個命令對象,并執(zhí)行原始SQL查詢
$connection = Yii::$app->db;
$command = $connection->createCommand("
SELECT p.id, p.title, u.username
FROM post p LEFT JOIN user u ON p.author_id = u.id
WHERE p.status = 1 AND u.role = 'admin'
ORDER BY p.created_at DESC
LIMIT 10 OFFSET 0
");
$posts = $command->queryAll();</pre><p>這個例子中,我們首先創(chuàng)建了一個Command對象,并使用<code>setSql()
方法指定一條原始的SQL查詢語句。該語句將post
表和user
表進行左連接,查詢出所有狀態(tài)為1且用戶角色為“admin”的文章,并按照發(fā)布時間倒序排序,返回前10條記錄。最后,我們使用queryAll()
方法執(zhí)行該查詢,并返回所有符合要求的記錄。
總結:
在Yii框架中,我們可以使用多種方式來訪問數(shù)據(jù)庫中的數(shù)據(jù),包括Active Record查詢、Query Builder查詢、命令查詢和原始SQL查詢。不同的查詢構建器適用于不同的查詢場景,我們需要根據(jù)實際需求來選擇最合適的查詢方式。通過本文的介紹,相信讀者已經(jīng)對Yii框架中的數(shù)據(jù)查詢有了更深入的了解,希望對大家在實際開發(fā)中使用Yii框架有所幫助。
The above is the detailed content of Data query in Yii framework: access data efficiently. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Features and Advantages of C Language: Why is it one of the most popular programming languages? As a general-purpose high-level programming language, C language has many unique features and advantages, which is why it has become one of the most popular programming languages. This article will explore the characteristics and advantages of C language, as well as its wide application in various fields. First of all, C language has concise syntax and clear structure. Compared with other programming languages, the syntax of C language is relatively simple and easy to understand and learn. It uses the characteristics of natural language to enable programmers to

Functions and features of Go language Go language, also known as Golang, is an open source programming language developed by Google. It was originally designed to improve programming efficiency and maintainability. Since its birth, Go language has shown its unique charm in the field of programming and has received widespread attention and recognition. This article will delve into the functions and features of the Go language and demonstrate its power through specific code examples. Native concurrency support The Go language inherently supports concurrent programming, which is implemented through the goroutine and channel mechanisms.

Title: Efficient Practice Guide for Go Language Encoding Conversion In daily software development, we often encounter the need to convert text in different encodings. As an efficient and modern programming language, Go language provides a rich standard library and built-in functions, making it very simple and efficient to implement text encoding conversion. This article will introduce practical guidelines on how to perform encoding conversion in the Go language and provide specific code examples. 1.UTF-8 encoding and string conversion In Go language, strings use UTF-8 encoding by default

C drive space is running out! 5 efficient cleaning methods revealed! In the process of using computers, many users will encounter a situation where the C drive space is running out. Especially after storing or installing a large number of files, the available space of the C drive will decrease rapidly, which will affect the performance and running speed of the computer. At this time, it is very necessary to clean up the C drive. So, how to clean up C drive efficiently? Next, this article will reveal 5 efficient cleaning methods to help you easily solve the problem of C drive space shortage. 1. Clean up temporary files. Temporary files are temporary files generated when the computer is running.

The main differences between Laravel and Yii are design concepts, functional characteristics and usage scenarios. 1.Laravel focuses on the simplicity and pleasure of development, and provides rich functions such as EloquentORM and Artisan tools, suitable for rapid development and beginners. 2.Yii emphasizes performance and efficiency, is suitable for high-load applications, and provides efficient ActiveRecord and cache systems, but has a steep learning curve.

Python and C++ are two popular programming languages, each with its own advantages and disadvantages. For people who want to learn programming, choosing to learn Python or C++ is often an important decision. This article will explore the learning costs of Python and C++ and discuss which language is more worthy of the time and effort. First, let's start with Python. Python is a high-level, interpreted programming language known for its ease of learning, clear code, and concise syntax. Compared to C++, Python

The steps to containerize and deploy Yii applications using Docker include: 1. Create a Dockerfile and define the image building process; 2. Use DockerCompose to launch Yii applications and MySQL database; 3. Optimize image size and performance. This involves not only specific technical operations, but also understanding the working principles and best practices of Dockerfile to ensure efficient and reliable deployment.

[Interpretation of new features of Go language: To make programming more efficient, specific code examples are needed] In recent years, Go language has attracted much attention in the field of software development, and its simple and efficient design concept has attracted more and more developers. As a statically typed programming language, Go language continues to introduce new features to improve development efficiency and simplify the code writing process. This article will provide an in-depth explanation of the latest features of the Go language and discuss how to experience the convenience brought by these new features through specific code examples. Modular development (GoModules) Go language from 1
