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 分页分组类
Dec 10 PHP
php park、unpark、ord 函数使用方法(二进制流接口应用实例)
Oct 19 PHP
PHP中对用户身份认证实现两种方法
Jun 04 PHP
二进制交叉权限微型php类分享
Feb 07 PHP
PHP中提问频率最高的11个面试题和答案
Sep 02 PHP
php中cookie实现二级域名可访问操作的方法
Nov 11 PHP
postfixadmin忘记密码后的修改密码方法详解
Jul 20 PHP
php实现博客,论坛图片防盗链的方法
Oct 15 PHP
微信公众号开发客服接口实例代码
Oct 21 PHP
laravel中命名路由的使用方法
Feb 24 PHP
PHP多进程简单实例小结
Nov 09 PHP
如何用PHP websocket实现网页实时聊天
May 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
php面向对象全攻略 (十六) 对象的串行化
2009/09/30 PHP
30个php操作redis常用方法代码例子
2014/07/05 PHP
PHP中配置IIS7实现基本身份验证的方法
2015/09/24 PHP
完美解决phpdoc导出文档中@package的warning及Error的错误
2016/05/17 PHP
WordPress分页伪静态加html后缀
2016/06/08 PHP
PHP实现新型冠状病毒疫情实时图的实例
2020/02/04 PHP
实例讲解PHP表单
2020/06/10 PHP
dojo 之基础篇(三)之向服务器发送数据
2007/03/24 Javascript
JQuery入门——事件切换之hover()方法应用介绍
2013/02/05 Javascript
Javascript 实现图片无缝滚动
2014/12/19 Javascript
Backbone.js的Hello World程序实例
2015/06/19 Javascript
window.onload使用指南
2015/09/13 Javascript
如何理解jQuery中的ajaxSubmit方法
2017/03/13 Javascript
JS传播事件、取消事件默认行为、阻止事件传播详解
2017/08/14 Javascript
10个在JavaScript开发中常遇到的BUG
2017/12/18 Javascript
vue树形结构获取键值的方法示例
2018/06/21 Javascript
详解Vue CLI3配置之filenameHashing使用和源码设计使用和源码设计
2018/08/31 Javascript
微信小程序搜索框样式并实现跳转到搜索页面(小程序搜索功能)
2020/03/10 Javascript
python数据预处理之将类别数据转换为数值的方法
2017/07/05 Python
python多线程之事件Event的使用详解
2018/04/27 Python
解决Pycharm运行时找不到文件的问题
2018/10/29 Python
python3使用QQ邮箱发送邮件
2020/05/20 Python
对python中字典keys,values,items的使用详解
2019/02/03 Python
Python File(文件) 方法整理
2019/02/18 Python
详解pytorch 0.4.0迁移指南
2019/06/16 Python
使用Python中的reduce()函数求积的实例
2019/06/28 Python
pyinstaller参数介绍以及总结详解
2019/07/12 Python
浅谈matplotlib中FigureCanvasXAgg的用法
2020/06/16 Python
Hotels.com南非:酒店预订
2017/11/02 全球购物
文秘专业毕业生就业推荐信
2013/11/08 职场文书
银行介绍信范文
2014/01/10 职场文书
2014年保洁工作总结
2014/11/24 职场文书
师德先进个人材料
2014/12/20 职场文书
2015年见习期个人工作总结
2015/05/28 职场文书
务工证明怎么写
2015/06/18 职场文书
管理者日常工作必备:22条企业管理流程模板!
2019/07/12 职场文书