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作的文本留言本的例子(二)
Oct 09 PHP
一个简单的php实现的MySQL数据浏览器
Mar 11 PHP
php使HTML标签自动补全闭合函数代码
Oct 04 PHP
PHP与MongoDB简介|安全|M+PHP应用实例详解
Jun 17 PHP
PHP+memcache实现消息队列案例分享
May 21 PHP
PHP反射使用实例和PHP反射API的中文说明
Jul 02 PHP
php函数serialize()与unserialize()用法实例
Nov 06 PHP
php脚本运行时的超时机制详解
Feb 17 PHP
老生常谈PHP 文件写入和读取(必看篇)
May 22 PHP
Laravel模型事件的实现原理详解
Mar 14 PHP
Yii框架中使用PHPExcel的方法分析
Jul 25 PHP
PHP连续签到功能实现方法详解
Dec 04 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数组最大值,最小值的代码
2011/10/31 PHP
PHP的引用详解
2015/02/22 PHP
浅谈php提交form表单
2015/07/01 PHP
Symfony学习十分钟入门经典教程
2016/02/03 PHP
php构造函数与析构函数
2016/04/23 PHP
在模板页面的js使用办法
2010/04/01 Javascript
Jquery 动态添加按钮实现代码
2010/05/06 Javascript
jquery提升性能最佳实践小结
2010/12/06 Javascript
js滚动条回到顶部的代码
2011/12/06 Javascript
探讨JQUERY JSON的反序列化类 using问题的解决方法
2013/12/19 Javascript
轻松创建nodejs服务器(4):路由
2014/12/18 NodeJs
jquery任意位置浮动固定层插件用法实例
2015/05/29 Javascript
javascript伸缩菜单栏实现代码分享
2015/11/12 Javascript
javascript鼠标右键菜单自定义效果
2020/12/08 Javascript
jquery操作select元素和option的实例代码
2016/02/03 Javascript
js+css实现select的美化效果
2016/03/24 Javascript
Jquery Easyui进度条组件Progress使用详解(8)
2020/03/26 Javascript
使用selenium抓取淘宝的商品信息实例
2018/02/06 Javascript
vue router总结 $router和$route及router与 router与route区别
2019/07/05 Javascript
解决Antd 里面的select 选择框联动触发的问题
2020/10/24 Javascript
Python使用BeautifulSoup库解析HTML基本使用教程
2016/03/31 Python
Android 兼容性问题:java.lang.UnsupportedOperationException解决办法
2017/03/19 Python
flask使用session保存登录状态及拦截未登录请求代码
2018/01/19 Python
使用 Python 实现微信群友统计器的思路详解
2018/09/26 Python
Python实现投影法分割图像示例(二)
2020/01/17 Python
如何在Python 游戏中模拟引力
2020/03/27 Python
瑞典领先的汽车零部件网上零售商:bildelaronline24.se
2017/01/12 全球购物
中科创达面试题
2016/12/28 面试题
农行实习自我鉴定
2013/09/22 职场文书
办公室文书岗位职责
2013/12/16 职场文书
自我鉴定怎么写
2014/01/12 职场文书
家庭教育先进个人事迹材料
2014/01/24 职场文书
药品营销专业毕业生自荐信
2014/07/02 职场文书
机关干部个人对照检查材料思想汇报
2014/09/28 职场文书
小学信息技术教学反思
2016/02/16 职场文书
创业计划书之旅游网站
2019/09/06 职场文书