• Yii createCommand CURD操作


    本文用作工作记录,也许有人会问为什么不用 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.         ]);  
  • 相关阅读:
    工具类
    开发中用到的工具
    项目中另外添加有用的文件:404
    如何组织项目结构:约定优于配置
    媒体查询
    响应式网站开发需要掌握的技术及国内外主流浏览器
    响应式网站概念
    sql存储过程,raisError后要return错误代码,过程最后要return 0
    delphi用TAdoStoredProc调用存储过程,兼容sql2005、2008、2014的远程事务问题
    网页视频下载牛逼工具,支持各种格式转换,比如腾讯视频格式qlv转mp4
  • 原文地址:https://www.cnblogs.com/xieqian111/p/5253989.html
Copyright © 2020-2023  润新知