Yii2数据库操作常用方法小结


Posted in PHP onMay 04, 2017

本文实例讲述了Yii2数据库操作常用方法。分享给大家供大家参考,具体如下:

查询:

// find the customers whose primary key value is 10
$customers = Customer::findAll(10);
$customer = Customer::findOne(10);
// the above code is equivalent to:
$customers = Customer::find()->where(['id' => 10])->all();
// find the customers whose primary key value is 10, 11 or 12.
$customers = Customer::findAll([10, 11, 12]);
$customers = Customer::find()->where(['IN','id',[10,11,12]])->all();
// the above code is equivalent to:
$customers = Customer::find()->where(['id' => [10, 11, 12]])->all();
// find customers whose age is 30 and whose status is 1
$customers = Customer::findAll(['age' => 30, 'status' => 1]);
// the above code is equivalent to:
$customers = Customer::find()->where(['age' => 30, 'status' => 1])->all();
// use params binding
$customers = Customer::find()->where('age=:age AND status=:status')->addParams([':age'=>30,':status'=>1])->all();
// use index
$customers = Customer::find()->indexBy('id')->where(['age' => 30, 'status' => 1])->all();
// get customers count
$count = Customer::find()->where(['age' => 30, 'status' => 1])->count();
// add addition condition
$customers = Customer::find()->where(['age' => 30, 'status' => 1])->andWhere('score > 100')->orderBy('id DESC')->offset(5)->limit(10)->all();
// find by sql
$customers = Customer::findBySql('SELECT * FROM customer WHERE age=30 AND status=1 AND score>100 ORDER BY id DESC LIMIT 5,10')->all();

修改:

// update status for customer-10
$customer = Customer::findOne(10);
$customer->status = 1;
$customer->update();
// the above code is equivalent to:
Customer::updateAll(['status' => 1], 'id = :id',[':id'=>10]);

删除:

// delete customer-10
Customer::findOne(10)->delete();
// the above code is equivalent to:
Customer::deleteAll(['status' => 1], 'id = :id',[':id'=>10]);

----------------使用子查询----------------------

$subQuery = (new Query())->select('COUNT(*)')->from('customer');
// SELECT `id`, (SELECT COUNT(*) FROM `customer`) AS `count` FROM `customer`
$query = (new Query())->select(['id', 'count' => $subQuery])->from('customer');

----------------手写SQL-----------------------

// select
$customers = Yii::$app->db->createCommand('SELECT * FROM customer')->queryAll();
// update
Yii::$app->db->createCommand()->update('customer',['status'=>1],'id=10')->execute();
// delete
Yii::$app->db->createCommand()->delete('customer','id=10')->execute();
//transaction
// outer
$transaction1 = $connection->beginTransaction();
try {
  $connection->createCommand($sql1)->execute();
  // internal
  $transaction2 = $connection->beginTransaction();
  try {
    $connection->createCommand($sql2)->execute();
    $transaction2->commit();
  } catch (Exception $e) {
    $transaction2->rollBack();
  }
  $transaction1->commit();
} catch (Exception $e) {
  $transaction1->rollBack();
}

---------------主从配置----------------------

[
  'class' => 'yii\db\Connection',
  // master
  'dsn' => 'dsn for master server',
  'username' => 'master',
  'password' => '',
  // slaves
  'slaveConfig' => [
    'username' => 'slave',
    'password' => '',
    'attributes' => [
      // use a smaller connection timeout
      PDO::ATTR_TIMEOUT => 10,
    ],
  ],
  'slaves' => [
    ['dsn' => 'dsn for slave server 1'],
    ['dsn' => 'dsn for slave server 2'],
    ['dsn' => 'dsn for slave server 3'],
    ['dsn' => 'dsn for slave server 4'],
  ],
]

希望本文所述对大家基于Yii框架的PHP程序设计有所帮助。

PHP 相关文章推荐
用PHP实现读取和编写XML DOM代码
Apr 07 PHP
深入php socket的讲解与实例分析
Jun 13 PHP
phpmailer中文乱码问题的解决方法
Apr 22 PHP
PHP基于GD库的缩略图生成代码(支持jpg,gif,png格式)
Jun 19 PHP
Thinkphp的volist标签嵌套循环使用教程
Jul 08 PHP
php实现获取文件mime类型的方法
Feb 11 PHP
php计算title标题相似比的方法
Jul 29 PHP
php创建桌面快捷方式实现方法
Dec 31 PHP
php 判断字符串编码是utf-8 或gb2312实例
Nov 01 PHP
深入理解PHP的远程多会话调试
Sep 21 PHP
PHP空值检测函数与方法汇总
Nov 19 PHP
PHP两个n位的二进制整数相加问题的解决
Aug 26 PHP
Yii2中添加全局函数的方法分析
May 04 #PHP
Yii2表单事件之Ajax提交实现方法
May 04 #PHP
PHP经典实用正则表达式小结
May 04 #PHP
PHP实现的简单异常处理类示例
May 04 #PHP
PHP基于新浪IP库获取IP详细地址的方法
May 04 #PHP
PHP 无限级分类
May 04 #PHP
PHP实现中国公民身份证号码有效性验证示例代码
May 03 #PHP
You might like
让你的WINDOWS同时支持MYSQL4,MYSQL4.1,MYSQL5X
2006/12/06 PHP
PHP 中关于ord($str)>0x80的详细说明
2012/09/23 PHP
如何使用php输出时间格式
2013/08/31 PHP
网页自动跳转代码收集
2009/09/27 Javascript
JavaScript Event学习补遗 addEventSimple
2010/02/11 Javascript
javascript处理table表格的代码
2010/12/06 Javascript
基于jQuery的试卷自动排版系统实现代码
2011/01/06 Javascript
为原生js Array增加each方法
2012/04/07 Javascript
Jquery 表单验证类介绍与实例
2013/06/09 Javascript
JavaScript数据结构和算法之图和图算法
2015/02/11 Javascript
简介JavaScript中Math.LOG10E属性的使用
2015/06/14 Javascript
JS日期格式化之javascript Date format
2015/10/01 Javascript
jquery实现网页的页面平滑滚动效果代码
2015/11/02 Javascript
jQuery验证插件validate使用详解
2016/05/11 Javascript
js实现水平滚动菜单导航
2017/07/21 Javascript
用ES6写全屏滚动插件的示例代码
2018/05/02 Javascript
JavaScript中toLocaleString()和toString()的区别实例分析
2018/08/14 Javascript
微信小程序实现单选功能
2018/10/30 Javascript
Vue的Eslint配置文件eslintrc.js说明与规则介绍
2020/02/03 Javascript
JQuery省市联动效果实现过程详解
2020/05/08 jQuery
JavaScript中继承原理与用法实例入门
2020/05/09 Javascript
c++生成dll使用python调用dll的方法
2014/01/20 Python
python通过索引遍历列表的方法
2015/05/04 Python
Python模拟登录的多种方法(四种)
2018/06/01 Python
Python 判断文件或目录是否存在的实例代码
2018/07/19 Python
python语言实现贪吃蛇游戏
2020/11/13 Python
python基于socket模拟实现ssh远程执行命令
2020/12/05 Python
HTML5 Plus 实现手机APP拍照或相册选择图片上传功能
2016/07/13 HTML / CSS
城野医生官方海外旗舰店:风靡亚洲毛孔收敛水
2018/04/26 全球购物
波兰在线香水店:Perfumy.pl
2019/08/12 全球购物
Piercing Pagoda官网:耳环、戒指、项链、手链等
2020/09/28 全球购物
求最大连续递增数字串(如"ads3sl456789DF3456ld345AA"中的"456789")
2015/09/11 面试题
linux比较文件内容的命令是什么
2013/03/04 面试题
2016应届毕业生就业指导课心得体会
2016/01/15 职场文书
高中班主任寄语
2019/06/21 职场文书
Python实现老照片修复之上色小技巧
2021/10/16 Python