yii2框架怎么写子查询

admin3年前PHP502

在yii中使用子查询的方法

第一步,先创建一个子查询,可以是基于 yii\db\Query 创建,也可以基于Model。

$subQuery = Order::find()

->where(['user_id' => $userId])

->andWhere(['status' => $status]);

也可以增加排序,分页,比如:

$subQuery->orderBy(['id' => SORT_ASC])

->offset($offset)

->limit($pageSize);

接下来就可以在我们的主查询中使用这个子查询了,只要是在mysql中可以写子查询的地方,都可以直接使用这个子查询。

$list = (new Query())->select($field)

->from(['order' => $subQuery]) // 在这里使用了子查询

->leftJoin(['goods' => OrderGoods::tableName()], 'order.id = goods.order_id')

->createCommand()

->queryAll();

最终生成的语句

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

相关文章

腾讯云点播总结

防盗链设置 https://cloud.tencent.com/document/product/266/14047超级播放器签名 https://cloud.tencent.com/document...

phpqrcode生成二维码,并在底部加上图片

Vendor('phpqrcode.phpqrcode');$font = ROOT_PATH.'public/static/common/font/hgzb.ttf'...

php连接sqlite

<?phpheader("Content-type:text/html;charset=utf-8");set_time_limit(0);class SQLite{&nbs...

安装Composer报错php_igbinary.dll' - 找不到指定的模块。

首先去php\php-7.1.13-nts\ext中找,并未发现有php_igbinary.dll文件,然后去该网站下载适合自己的文件 网址:https://windows.php.net/downl...

阿里云虚拟电话保护

下载安装好compser下载DEMO,参考网址https://next.api.aliyun.com/api/Dyplsapi/2017-05-25/BindAxb?spm=a2c4g.1118662...

宝塔面板无法执行composer命令

请选择root用户执行...

发表评论    

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。