search
HomePHP FrameworkYIIData query in Yii framework: access data efficiently

Data query in Yii framework: access data efficiently

Jun 21, 2023 am 11:22 AM
yiiEfficientdata query

Yii 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.

  1. 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:

//创建一个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

orderBy()

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”的文章,并按照发布时间倒序排序,返回前10条记录 $posts = Post::find()-&gt;where(['like', 'title', 'Yii']) -&gt;andWhere(['author' =&gt; 'admin']) -&gt;orderBy(['created_at' =&gt; SORT_DESC]) -&gt;limit(10) -&gt;offset(0) -&gt;all();</pre>In this example, we use the find() method to create an Active Record query object, and then use

where()

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

Query Builder is another commonly used data access method in the Yii framework. It provides a chain call method to build SQL query statements. , more suitable for complex query requirements. In the Yii framework, we can use the
    Yii::$app->db->createCommand()
  1. method to create a Query Builder object, and then use a series of methods of the object to build query statements.
The following is an example of a Query Builder query:

//创建一个查询构建器对象,并构建查询语句
$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);

//执行查询,并返回结果集
$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
  1. execute()
  2. method of the object to execute SQL statements.

The following is an example of a command query: <pre class='brush:php;toolbar:false;'>//创建一个命令对象,并执行SQL语句 Yii::$app-&gt;db-&gt;createCommand() -&gt;update('post', ['status' =&gt; 1], 'author = &quot;admin&quot;') -&gt;execute();</pre>In this example, we first use the Yii::$app->db->createCommand() method Created a Command object, and then used the object's

update()

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 queryIn 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

Yii::$app->db->createCommand()
    method to create a Command object, and then use the
  1. setSql()
  2. method of the object To specify the original SQL statement, and use the
queryAll()

method to execute the query. The following is an example of a raw SQL query:<pre class='brush:php;toolbar:false;'>//创建一个命令对象,并执行原始SQL查询 $connection = Yii::$app-&gt;db; $command = $connection-&gt;createCommand(&quot; 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 &quot;); $posts = $command-&gt;queryAll();</pre><p>这个例子中,我们首先创建了一个Command对象,并使用<code>setSql()方法指定一条原始的SQL查询语句。该语句将post表和user表进行左连接,查询出所有状态为1且用户角色为“admin”的文章,并按照发布时间倒序排序,返回前10条记录。最后,我们使用queryAll()方法执行该查询,并返回所有符合要求的记录。

总结:

在Yii框架中,我们可以使用多种方式来访问数据库中的数据,包括Active Record查询、Query Builder查询、命令查询和原始SQL查询。不同的查询构建器适用于不同的查询场景,我们需要根据实际需求来选择最合适的查询方式。通过本文的介绍,相信读者已经对Yii框架中的数据查询有了更深入的了解,希望对大家在实际开发中使用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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Is it easy to migrate a Laravel Project to Yii?Is it easy to migrate a Laravel Project to Yii?May 09, 2025 am 12:01 AM

Migratingalaravel Projecttoyiiishallingbutachieffable WITHIEFLEFLANT.1) Mapoutlaravel component likeroutes, Controllers, Andmodels.2) Translatelaravel's SartisancommandeloequentTooyii's giiandetiverecordeba

Essential Soft Skills for Yii Developers: Communication and CollaborationEssential Soft Skills for Yii Developers: Communication and CollaborationMay 08, 2025 am 12:11 AM

Soft skills are crucial to Yii developers because they facilitate team communication and collaboration. 1) Effective communication ensures that the project is progressing smoothly, such as through clear API documentation and regular meetings. 2) Collaborate to enhance team interaction through Yii's tools such as Gii to improve development efficiency.

Laravel MVC : What are the best benefits?Laravel MVC : What are the best benefits?May 07, 2025 pm 03:53 PM

Laravel'sMVCarchitectureoffersenhancedcodeorganization,improvedmaintainability,andarobustseparationofconcerns.1)Itkeepscodeorganized,makingnavigationandteamworkeasier.2)Itcompartmentalizestheapplication,simplifyingtroubleshootingandmaintenance.3)Itse

Yii: Is It Still Relevant in Modern Web Development?Yii: Is It Still Relevant in Modern Web Development?May 01, 2025 am 12:27 AM

Yiiremainsrelevantinmodernwebdevelopmentforprojectsneedingspeedandflexibility.1)Itoffershighperformance,idealforapplicationswherespeediscritical.2)Itsflexibilityallowsfortailoredapplicationstructures.However,ithasasmallercommunityandsteeperlearningcu

The Longevity of Yii: Reasons for Its EnduranceThe Longevity of Yii: Reasons for Its EnduranceApr 30, 2025 am 12:22 AM

Yii frameworks remain strong in many PHP frameworks because of their efficient, simplicity and scalable design concepts. 1) Yii improves development efficiency through "conventional optimization over configuration"; 2) Component-based architecture and powerful ORM system Gii enhances flexibility and development speed; 3) Performance optimization and continuous updates and iterations ensure its sustained competitiveness.

Yii: Exploring Its Current UsageYii: Exploring Its Current UsageApr 29, 2025 am 12:52 AM

Yii is still suitable for projects that require high performance and flexibility in modern web development. 1) Yii is a high-performance framework based on PHP, following the MVC architecture. 2) Its advantages lie in its efficient, simplified and component-based design. 3) Performance optimization is mainly achieved through cache and ORM. 4) With the emergence of the new framework, the use of Yii has changed.

Yii and PHP: Developing Dynamic WebsitesYii and PHP: Developing Dynamic WebsitesApr 28, 2025 am 12:09 AM

Yii and PHP can create dynamic websites. 1) Yii is a high-performance PHP framework that simplifies web application development. 2) Yii provides MVC architecture, ORM, cache and other functions, which are suitable for large-scale application development. 3) Use Yii's basic and advanced features to quickly build a website. 4) Pay attention to configuration, namespace and database connection issues, and use logs and debugging tools for debugging. 5) Improve performance through caching and optimization queries, and follow best practices to improve code quality.

Yii's Features: Examining Its AdvantagesYii's Features: Examining Its AdvantagesApr 27, 2025 am 12:03 AM

The Yii framework stands out in the PHP framework, and its advantages include: 1. MVC architecture and component design to improve code organization and reusability; 2. Gii code generator and ActiveRecord to improve development efficiency; 3. Multiple caching mechanisms to optimize performance; 4. Flexible RBAC system to simplify permission management.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.