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中uploaded_files函数使用方法详解
Mar 09 PHP
php数组转换js数组操作及json_encode的用法详解
Oct 26 PHP
php $_SERVER windows系统与linux系统下的区别说明
Feb 14 PHP
PHP文件读写操作相关函数总结
Nov 18 PHP
PHP判断是否为空的几个函数对比
Apr 21 PHP
thinkphp命名空间用法实例详解
Dec 30 PHP
PHP类的特性实例分析
Sep 28 PHP
Yii统计不同类型邮箱数量的方法
Oct 18 PHP
thinkphp利用模型通用数据编辑添加和删除的实例代码
Nov 20 PHP
PHP中Notice错误常见解决方法
Apr 28 PHP
ThinkPHP中获取指定日期后工作日的具体日期方法
Oct 14 PHP
PHP图像处理技术实例总结【绘图、水印、验证码、图像压缩】
Dec 08 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
德劲1104的电路分析与改良
2021/03/01 无线电
一个更简单的无限级分类菜单代码
2007/01/16 PHP
PHP中调用ASP.NET的WebService的代码
2011/04/22 PHP
PHP 时间日期操作实战
2011/08/26 PHP
header导出Excel应用示例
2014/01/24 PHP
php创建和删除目录函数介绍和递归删除目录函数分享
2014/11/18 PHP
php微信开发之带参数二维码的使用
2016/08/03 PHP
PHPWind9.0手动屏蔽验证码解决后台关闭验证码但是依然显示的问题
2016/08/12 PHP
PHP性能分析工具xhprof的安装使用与注意事项
2017/12/19 PHP
Laravel 数据库加密及数据库表前缀配置方法
2019/10/10 PHP
5秒后跳转效果(setInterval/SetTimeOut)
2013/05/03 Javascript
IE的事件传递-event.cancelBubble示例介绍
2014/01/12 Javascript
JS实现鼠标框选效果完整实例
2016/06/20 Javascript
JS实现表单多文件上传样式美化支持选中文件后删除相关项
2016/09/30 Javascript
原生JS版和jquery版实现checkbox的全选/全不选/点选/行内点选(Mr.Think)
2016/10/29 Javascript
JS canvas绘制五子棋的棋盘
2020/05/28 Javascript
史上最为详细的javascript继承(推荐)
2019/05/18 Javascript
微信小程序实现聊天室
2020/08/21 Javascript
Python 3.x 新特性及10大变化
2015/06/12 Python
Python cookbook(数据结构与算法)字典相关计算问题示例
2018/02/18 Python
使用python对excle和json互相转换的示例
2018/10/23 Python
pyqt5实现俄罗斯方块游戏
2019/01/11 Python
Python3.5基础之NumPy模块的使用图文与实例详解
2019/04/24 Python
Django使用中间键实现csrf认证详解
2019/07/22 Python
微信公众号token验证失败解决方案
2019/07/22 Python
django之静态文件 django 2.0 在网页中显示图片的例子
2019/07/28 Python
PyTorch中Tensor的拼接与拆分的实现
2019/08/18 Python
python如何修改文件时间属性
2021/02/05 Python
Banana Republic欧盟:美国都市简约风格的代表品牌
2018/05/09 全球购物
一套中级Java程序员笔试题
2015/01/14 面试题
生物化工专业个人自荐信
2013/09/26 职场文书
大学生军训自我评价分享
2013/11/09 职场文书
单位消防安全制度
2014/01/12 职场文书
安全资金保障制度
2014/01/23 职场文书
2015年度团总支工作总结
2015/04/23 职场文书
Java 超详细讲解十大排序算法面试无忧
2022/04/08 Java/Android