Home >PHP Framework >YII >How to write subquery in yii2 framework

How to write subquery in yii2 framework

爱喝马黛茶的安东尼
爱喝马黛茶的安东尼Original
2019-12-09 13:52:305087browse

How to write subquery in yii2 framework

How to use subquery in Yii

The first step is to create a subquery, which can be Created based on yii\db\Query or based on Model.

$subQuery = Order::find()
->where(['user_id' => $userId])
->andWhere(['status' => $status]);

You can also add sorting and paging, for example:

$subQuery->orderBy(['id' => SORT_ASC])
->offset($offset)
->limit($pageSize);

Then we can use this subquery in our main query, as long as it is a place where subqueries can be written in mysql , you can use this subquery directly.

$list = (new Query())->select($field)
->from(['order' => $subQuery]) // 在这里使用了子查询
->leftJoin(['goods' => OrderGoods::tableName()], 'order.id = goods.order_id')
->createCommand()
->queryAll();

Finally generated statement

SELECT
*
FROM
( SELECT
* 
FROM
`od_order` 
WHERE
( `user_id` = '1' ) 
ORDER BY
`id` ASC
LIMIT 10 OFFSET 1 
) `order`
LEFT JOIN `od_order_goods` `goods` ON `order`.id = goods.order_id

PHP Chinese website has a large number of free Yii introductory tutorials, everyone is welcome to learn!

The above is the detailed content of How to write subquery in yii2 framework. 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

Related articles

See more