本文用作工作记录,也许有人会问为什么不用 Yii 的 Model 去操作 DB,原因很简单,Yii 的 Model 写法上是方便了很多,但是会执行多余的 SQL,打开 Yii 的执行 log 就会发现。
打开跟踪log的方法,config/main.php中 log routes 中添加
[ 'class' => 'CWebLogRoute', ]
所以为了效率,为了 DB 服务器的性能考虑,还是使用 createCommand 的好。
insert
$row = Yii::app()->getDb()->createCommand()->insert('goods', array( 'good_name' => $goods_name, 'good_type' => $goods_type, 'price' => $price, 'buy_nums' => 0, 'commit_nums' => 0, 'create_time' => time(), ));
单表查询
$goodsTypes = Yii::app()->getDb()->createCommand() ->select('type_id, type_name') ->from('goods_type') ->where('status=:status', [ ':status' => 1 ]) ->queryAll();
$goods = Yii::app()->getDb()->createCommand()->from('goods g') ->select('g.good_id, g.good_name, gt.type_name, g.price, g.buy_nums, g.commit_nums, g.create_time') ->join('goods_type gt', 'g.good_type=gt.type_id') ->where('g.`status`=:status1 and gt.`status`=:status2', [ ':status1' => 1, ':status2' => 2 ]) ->order('g.create_time desc') ->queryAll();
$row = Yii::app()->getDb()->createCommand() ->delete('goods', "good_id=:good_id", array( ':good_id' => $goods_id, ));
$row = Yii::app()->getDb()->createCommand()->update('goods', [ 'good_name' => $goods_name, 'good_type' => $goods_type, 'price' => $price, ], "good_id=:good_id", [ ':good_id' => 1 ]);
就记录这点吧~