Yii createCommand CURD操作

来源:互联网 发布:nginx lua redis 灰度 编辑:程序博客网 时间:2024/05/21 09:03

本文用作工作记录,也许有人会问为什么不用 Yii 的 Model 去操作 DB,原因很简单,Yii 的 Model 写法上是方便了很多,但是会执行多余的 SQL,打开 Yii 的执行 log 就会发现。

打开跟踪log的方法,config/main.PHP中 log routes 中添加

[php] view plain copy
  1. [  
  2.     'class' => 'CWebLogRoute',  
  3. ]  

所以为了效率,为了 DB 服务器的性能考虑,还是使用 createCommand 的好。

insert

[php] view plain copy
  1. $row = Yii::app()->getDb()->createCommand()->insert('goods'array(  
  2.             'good_name' => $goods_name,  
  3.             'good_type' => $goods_type,  
  4.             'price' => $price,  
  5.             'buy_nums' => 0,  
  6.             'commit_nums' => 0,  
  7.             'create_time' => time(),  
  8.         ));  

select

单表查询

[php] view plain copy
  1. $goodsTypes = Yii::app()->getDb()->createCommand()  
  2.         ->select('type_id, type_name')  
  3.         ->from('goods_type')  
  4.         ->where('status=:status', [  
  5.             ':status' => 1  
  6.         ])  
  7.         ->queryAll();  


连表查询

[php] view plain copy
  1. $goods = Yii::app()->getDb()->createCommand()->from('goods g')  
  2.         ->select('g.good_id, g.good_name, gt.type_name, g.price, g.buy_nums, g.commit_nums, g.create_time')  
  3.         ->join('goods_type gt''g.good_type=gt.type_id')  
  4.         ->where('g.`status`=:status1 and gt.`status`=:status2', [  
  5.             ':status1' => 1,  
  6.             ':status2' => 2  
  7.         ])  
  8.         ->order('g.create_time desc')  
  9.         ->queryAll();  


delete

[php] view plain copy
  1. $row = Yii::app()->getDb()->createCommand()  
  2.         ->delete('goods'"good_id=:good_id"array(  
  3.             ':good_id' => $goods_id,  
  4.         ));  


update

[php] view plain copy
  1. $row = Yii::app()->getDb()->createCommand()->update('goods', [  
  2.     'good_name' => $goods_name,  
  3.     'good_type' => $goods_type,  
  4.     'price' => $price,  
  5.         ], "good_id=:good_id", [  
  6.     ':good_id' => 1  
  7.         ]);  
0 0