Yii增删改查

 

有人会问为什么不用 Yii 的 Model 去操作 DB,原因很简单,Yii 的 Model 写法上是方便了很多,但是会执行多余的 SQL,打开 Yii 的执行 log 就会发现。所以为了效率,为了 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(),
        ));
//select  单表查询
$goodsTypes = Yii::app()->getDb()->createCommand()
            ->select('type_id, type_name')
            ->from('goods_type')
            ->where('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`=1 and gt.`status`=1')
        ->order('g.create_time desc')
        ->queryAll();
//delete

$row = Yii::app()->getDb()->createCommand()
        ->delete('goods', "good_id=:good_id", array(
            ':good_id' => $goods_id,
        ));
//update

$row = Yii::app()->getDb()->createCommand()->update('goods', array(
    'good_name' => $goods_name,
    'good_type' => $goods_type,
    'price' => $price,
), "good_id='{$goods_id}'");

 

posted @ 2015-10-20 17:35  SunsCheung  阅读(147)  评论(0编辑  收藏  举报