How to query data in yii2
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!

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

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



DDREASE is a tool for recovering data from file or block devices such as hard drives, SSDs, RAM disks, CDs, DVDs and USB storage devices. It copies data from one block device to another, leaving corrupted data blocks behind and moving only good data blocks. ddreasue is a powerful recovery tool that is fully automated as it does not require any interference during recovery operations. Additionally, thanks to the ddasue map file, it can be stopped and resumed at any time. Other key features of DDREASE are as follows: It does not overwrite recovered data but fills the gaps in case of iterative recovery. However, it can be truncated if the tool is instructed to do so explicitly. Recover data from multiple files or blocks to a single

0.What does this article do? We propose DepthFM: a versatile and fast state-of-the-art generative monocular depth estimation model. In addition to traditional depth estimation tasks, DepthFM also demonstrates state-of-the-art capabilities in downstream tasks such as depth inpainting. DepthFM is efficient and can synthesize depth maps within a few inference steps. Let’s read about this work together ~ 1. Paper information title: DepthFM: FastMonocularDepthEstimationwithFlowMatching Author: MingGui, JohannesS.Fischer, UlrichPrestel, PingchuanMa, Dmytr

Download the latest version of 12306 ticket booking app. It is a travel ticket purchasing software that everyone is very satisfied with. It is very convenient to go wherever you want. There are many ticket sources provided in the software. You only need to pass real-name authentication to purchase tickets online. All users You can easily buy travel tickets and air tickets and enjoy different discounts. You can also start booking reservations in advance to grab tickets. You can book hotels or special car transfers. With it, you can go where you want to go and buy tickets with one click. Traveling is simpler and more convenient, making everyone's travel experience more comfortable. Now the editor details it online Provides 12306 users with a way to view historical ticket purchase records. 1. Open Railway 12306, click My in the lower right corner, and click My Order 2. Click Paid on the order page. 3. On the paid page

The performance of JAX, promoted by Google, has surpassed that of Pytorch and TensorFlow in recent benchmark tests, ranking first in 7 indicators. And the test was not done on the TPU with the best JAX performance. Although among developers, Pytorch is still more popular than Tensorflow. But in the future, perhaps more large models will be trained and run based on the JAX platform. Models Recently, the Keras team benchmarked three backends (TensorFlow, JAX, PyTorch) with the native PyTorch implementation and Keras2 with TensorFlow. First, they select a set of mainstream

Facing lag, slow mobile data connection on iPhone? Typically, the strength of cellular internet on your phone depends on several factors such as region, cellular network type, roaming type, etc. There are some things you can do to get a faster, more reliable cellular Internet connection. Fix 1 – Force Restart iPhone Sometimes, force restarting your device just resets a lot of things, including the cellular connection. Step 1 – Just press the volume up key once and release. Next, press the Volume Down key and release it again. Step 2 – The next part of the process is to hold the button on the right side. Let the iPhone finish restarting. Enable cellular data and check network speed. Check again Fix 2 – Change data mode While 5G offers better network speeds, it works better when the signal is weaker

How to check my academic qualifications on Xuexin.com? You can check your academic qualifications on Xuexin.com, but many users don’t know how to check their academic qualifications on Xuexin.com. Next, the editor brings you a graphic tutorial on how to check your academic qualifications on Xuexin.com. Interested users come and take a look! Xuexin.com usage tutorial: How to check your academic qualifications on Xuexin.com 1. Xuexin.com entrance: https://www.chsi.com.cn/ 2. Website query: Step 1: Click on the Xuexin.com address above to enter the homepage Click [Education Query]; Step 2: On the latest webpage, click [Query] as shown by the arrow in the figure below; Step 3: Then click [Login Academic Credit File] on the new page; Step 4: On the login page Enter the information and click [Login];

I cry to death. The world is madly building big models. The data on the Internet is not enough. It is not enough at all. The training model looks like "The Hunger Games", and AI researchers around the world are worrying about how to feed these data voracious eaters. This problem is particularly prominent in multi-modal tasks. At a time when nothing could be done, a start-up team from the Department of Renmin University of China used its own new model to become the first in China to make "model-generated data feed itself" a reality. Moreover, it is a two-pronged approach on the understanding side and the generation side. Both sides can generate high-quality, multi-modal new data and provide data feedback to the model itself. What is a model? Awaker 1.0, a large multi-modal model that just appeared on the Zhongguancun Forum. Who is the team? Sophon engine. Founded by Gao Yizhao, a doctoral student at Renmin University’s Hillhouse School of Artificial Intelligence.

This week, FigureAI, a robotics company invested by OpenAI, Microsoft, Bezos, and Nvidia, announced that it has received nearly $700 million in financing and plans to develop a humanoid robot that can walk independently within the next year. And Tesla’s Optimus Prime has repeatedly received good news. No one doubts that this year will be the year when humanoid robots explode. SanctuaryAI, a Canadian-based robotics company, recently released a new humanoid robot, Phoenix. Officials claim that it can complete many tasks autonomously at the same speed as humans. Pheonix, the world's first robot that can autonomously complete tasks at human speeds, can gently grab, move and elegantly place each object to its left and right sides. It can autonomously identify objects
