data query
User::find()->all(); 此方法返回所有数据; User::findOne($id); 此方法返回 主键 id=1 的一条数据(举个例子); User::find()->where(['name' => '小伙儿'])->one(); 此方法返回 ['name' => '小伙儿'] 的一条数据; User::find()->where(['name' => '小伙儿'])->all(); 此方法返回 ['name' => '小伙儿'] 的所有数据; User::find()->orderBy('id DESC')->all(); 此方法是排序查询; User::findBySql('SELECT * FROM user')->all(); 此方法是用 sql 语句查询 user 表里面的所有数据; User::findBySql('SELECT * FROM user')->one(); 此方法是用 sql 语句查询 user 表里面的一条数据; User::find()->andWhere(['sex' => '男', 'age' => '24'])->count('id'); 统计符合条件的总条数; User::find()->one(); 此方法返回一条数据; User::find()->all(); 此方法返回所有数据; User::find()->count(); 此方法返回记录的数量; User::find()->average(); 此方法返回指定列的平均值; User::find()->min(); 此方法返回指定列的最小值 ; User::find()->max(); 此方法返回指定列的最大值 ; User::find()->scalar(); 此方法返回值的第一行第一列的查询结果; User::find()->column(); 此方法返回查询结果中的第一列的值; User::find()->exists(); 此方法返回一个值指示是否包含查询结果的数据行; User::find()->batch(10); 每次取 10 条数据 User::find()->each(10); 每次取 10 条数据, 迭代查询
Multiple table query:
/* 多表联查 */ $model=new Customer(); $model->fiind()->join(‘LEFT JOIN‘,‘student‘,‘student.cid=customer.id‘) ->where(‘student.id‘=>\Yii::$app->user->id) ->andwhere(‘is_ok=1‘) ->one()
Related query
Using the AR method, you can also query the data table Related data (for example, selecting data from table A can pull out related data from table B). With AR, the returned related data join is just like joining the properties of the AR object to the related main table.
After establishing the association, you can obtain an array of Order objects through $customer->orders, which represents the order set of the current customer object.
Define the association using a getter method that can return the [[yii\db\ActiveQuery]] object. The [[yii\db\ActiveQuery]] object has information about the associated context, so you can only query the associated data. .
class Customer extends \yii\db\ActiveRecord { public function getOrders() { // 客户和订单通过 Order.customer_id -> id 关联建立一对多关系 return $this->hasMany(Order::className(), ['customer_id' => 'id']); } } class Order extends \yii\db\ActiveRecord { // 订单和客户通过 Customer.id -> customer_id 关联建立一对一关系 public function getCustomer() { return $this->hasOne(Customer::className(), ['id' => 'customer_id']); } }
The above uses the [[yii\db\ActiveRecord::hasMany()]] and [[yii\db\ActiveRecord::hasOne()]] methods. The above two examples are modeling examples of many-to-one relationships and one-to-one relationships in associated data respectively. For example, a customer has many orders, and one order only belongs to one customer. Both methods have two parameters and return [[yii\db\ActiveQuery]] objects.
After establishing the association, obtaining the associated data is as simple as obtaining the component attributes. Just execute the following corresponding getter methods:
// 取得客户的订单 $customer = Customer::findOne(1); $orders = $customer->orders; // $orders 是 Order 对象数组
The above code actually executes the following two SQL statements:
SELECT * FROM customer WHERE id=1; SELECT * FROM order WHERE customer_id=1;
Sometimes it is necessary to pass parameters in the related query. For example, if you do not need to return all the customer's orders, you only need to return the large orders whose purchase amount exceeds the set value. Declare a related data bigOrders through the following getter method:
class Customer extends \yii\db\ActiveRecord { public function getBigOrders($threshold = 100) { return $this->hasMany(Order::className(), ['customer_id' => 'id']) ->where('subtotal > :threshold', [':threshold' => $threshold]) ->orderBy('id'); } }
Join Query
When using a relational database, what is commonly done is to join multiple tables and explicitly use various JOIN queries. The query conditions and parameters of the JOIN SQL statement can be implemented by using [[yii\db\ActiveQuery::joinWith()]] to reuse the defined relationship and call it instead of using [[yii\db\ActiveQuery::join()]] Target.
// 查找所有订单并以客户 ID 和订单 ID 排序,并贪婪加载 "customer" 表 $orders = Order::find()->joinWith('customer')->orderBy('customer.id, order.id')->all(); // 查找包括书籍的所有订单,并以 `INNER JOIN` 的连接方式即时加载 "books" 表 $orders = Order::find()->innerJoinWith('books')->all();
The above method [[yii\db\ActiveQuery::innerJoinWith()|innerJoinWith()]] is to access the INNER JOIN type [[yii\db\ActiveQuery::joinWith()
|joinWith()]] shortcut.
You can connect one or more related relationships, you can freely use query conditions to related queries, and you can also nest connected related queries. For example:
// 连接多重关系 // 找出24小时内注册客户包含书籍的订单 $orders = Order::find()->innerJoinWith([ 'books', 'customer' => function ($query) { $query->where('customer.created_at > ' . (time() - 24 * 3600)); } ])->all(); // 连接嵌套关系:连接 books 表及其 author 列 $orders = Order::find()->joinWith('books.author')->all();
Behind the code, Yii first executes a JOIN SQL statement to find out the main models that meet the query conditions of the JOIN SQL statement, then executes a query statement for each relationship, and bing fills in the corresponding associated records.
The difference between [[yii\db\ActiveQuery::joinWith()|joinWith()]] and [[yii\db\ActiveQuery::with()|with()]] is that the former connects to the main model class and the data table of the associated model class to retrieve the main model, while the latter only queries and retrieves the main model class. Retrieve the main model
Because of this difference, you can apply query conditions that only work against a JOIN SQL statement. For example, filter the main model through the query conditions of the associated model. As in the previous example, you can use the columns of the associated table to select the main model data.
When using [[yii\db\ActiveQuery::joinWith()|joinWith( )]] method can respond to unambiguous column names. In the above examples, we useitem.id and order.id to disambiguate the id column references because both the order table and the items table include the id column.
When connecting to an association, the association uses instant loading by default. You can decide whether to use eager loading in the specified related query by passing the parameter $eagerLoading.
Default [[yii\db\ActiveQuery::joinWith()|joinWith()]] uses left joins to join related tables. You can also pass the $joinType parameter to customize the join type. You can also use [[yii\db\ActiveQuery::innerJoinWith()|innerJoinWith()]].
Yii2 Paging
Any method in the controller CommentController, here my method is actionComment();
use yii\data\Pagination; use app\models\Comment; public function actionComment(){ $data = Comment::find()->andWhere(['id' => '10']); $pages = new Pagination(['totalCount' =>$data->count(), 'pageSize' => '2']); $model = $data->offset($pages->offset)->limit($pages->limit)->all(); return $this->render('comment',[ 'model' => $model, 'pages' => $pages, ]); }
view Code inside
<?php use yii\widgets\LinkPager; ?> foreach($model as $key=>$val) { 这里就是遍历数据 } <?= LinkPager::widget(['pagination' => $pages]); ?>
in() operation
SELECT * FROM `categ_price` WHERE `id` IN (9, 11)
$categ_price_id=[9>1,11=>3] $categPriceModel= \common\models\CategPrice::find()->where(['id' =>array_keys($categ_price_id)])->all(); #>where(['id' => [1, 2, 3]])
not in() operation
SELECT * FROM `shop` WHERE (status=1) AND (`id` NOT IN (88, 93))
$shopModel= Shop::find()->where('status=1')->andWhere(['not in','id',[88,98]])->all();
PHP中文网, there are a lot of free Yii introductory tutorials, everyone is welcome to learn!
The above is the detailed content of How to query data in yii2. For more information, please follow other related articles on the PHP Chinese website!

YiiremainspopularbutislessfavoredthanLaravel,withabout14kGitHubstars.ItexcelsinperformanceandActiveRecord,buthasasteeperlearningcurveandasmallerecosystem.It'sidealfordevelopersprioritizingefficiencyoveravastecosystem.

Yii is a high-performance PHP framework that is unique in its componentized architecture, powerful ORM and excellent security. 1. The component-based architecture allows developers to flexibly assemble functions. 2. Powerful ORM simplifies data operation. 3. Built-in multiple security functions to ensure application security.

Yii framework adopts an MVC architecture and enhances its flexibility and scalability through components, modules, etc. 1) The MVC mode divides the application logic into model, view and controller. 2) Yii's MVC implementation uses action refinement request processing. 3) Yii supports modular development and improves code organization and management. 4) Use cache and database query optimization to improve performance.

Strategies to improve Yii2.0 application performance include: 1. Database query optimization, using QueryBuilder and ActiveRecord to select specific fields and limit result sets; 2. Caching strategy, rational use of data, query and page cache; 3. Code-level optimization, reducing object creation and using efficient algorithms. Through these methods, the performance of Yii2.0 applications can be significantly improved.

Developing a RESTful API in the Yii framework can be achieved through the following steps: Defining a controller: Use yii\rest\ActiveController to define a resource controller, such as UserController. Configure authentication: Ensure the security of the API by adding HTTPBearer authentication mechanism. Implement paging and sorting: Use yii\data\ActiveDataProvider to handle complex business logic. Error handling: Configure yii\web\ErrorHandler to customize error responses, such as handling when authentication fails. Performance optimization: Use Yii's caching mechanism to optimize frequently accessed resources and improve API performance.

In the Yii framework, components are reusable objects, and extensions are plugins added through Composer. 1. Components are instantiated through configuration files or code, and use dependency injection containers to improve flexibility and testability. 2. Expand the management through Composer to quickly enhance application functions. Using these tools can improve development efficiency and application performance.

Theming and Tempting of the Yii framework achieve website style and content generation through theme directories and views and layout files: 1. Theming manages website style and layout by setting theme directories, 2. Tempting generates HTML content through views and layout files, 3. Embed complex UI components using the Widget system, 4. Optimize performance and follow best practices to improve user experience and development efficiency.

When preparing for an interview with Yii framework, you need to know the following key knowledge points: 1. MVC architecture: Understand the collaborative work of models, views and controllers. 2. ActiveRecord: Master the use of ORM tools and simplify database operations. 3. Widgets and Helpers: Familiar with built-in components and helper functions, and quickly build the user interface. Mastering these core concepts and best practices will help you stand out in the interview.


Hot AI Tools

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

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

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 Linux new version
SublimeText3 Linux latest version

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

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

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.