Yii2数据库操作的各种写法
-------------------------------ActiveRecord----------------------------------------
查询:
// find the customers whose primary key value is 10
$customers = Customer::findAll();
$customer = Customer::findOne(); // the above code is equivalent to:
$customers = Customer::find()->where(['id' => ])->all(); // find the customers whose primary key value is 10, 11 or 12.
$customers = Customer::findAll([, , ]);
$customers = Customer::find()->where(['IN','id',[,,]])->all(); // the above code is equivalent to:
$customers = Customer::find()->where(['id' => [, , ]])->all(); // find customers whose age is 30 and whose status is 1
$customers = Customer::findAll(['age' => , 'status' => ]); // the above code is equivalent to:
$customers = Customer::find()->where(['age' => , 'status' => ])->all(); // use params binding
$customers = Customer::find()->where('age=:age AND status=:status')->addParams([':age'=>,':status'=>])->all(); // use index
$customers = Customer::find()->indexBy('id')->where(['age' => , 'status' => ])->all(); // get customers count
$count = Customer::find()->where(['age' => , 'status' => ])->count(); // add addition condition
$customers = Customer::find()->where(['age' => , 'status' => ])->andWhere('score > 100')->orderBy('id DESC')->offset()->limit()->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();
$customer->status = ;
$customer->update(); // the above code is equivalent to:
Customer::updateAll(['status' => ], 'id = :id',[':id'=>]);
删除:
// delete customer-10
Customer::findOne()->delete(); // the above code is equivalent to:
Customer::deleteAll(['status' => ], 'id = :id',[':id'=>]);
--------------------------------使用子查询------------------------------------------
$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'=>],'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 => ,
],
], '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'],
],
]
更多详情参考:
- http://www.yiiframework.com/doc-2.0/yii-db-activerecord.html
- http://www.yiiframework.com/doc-2.0/yii-db-queryinterface.html
- http://www.yiiframework.com/doc-2.0/yii-db-query.html
来源地址:http://www.getyii.com/topic/219
Yii2数据库操作的各种写法的更多相关文章
- Yii2 数据库操作汇总
对象操作 查询 //1.简单查询 $admin=Admin::model()->findAll($condition,$params); $admin=Admin::model()->fi ...
- yii2 数据库操作(转)
开始使用数据库首先需要配置数据库连接组件,通过添加 db 组件到应用配置实现("基础的" Web 应用是 config/web.php),DSN( Data Source Name ...
- yii2 数据库操作详解(转载)
开始使用数据库首先需要配置数据库连接组件,通过添加 db 组件到应用配置实现("基础的" Web 应用是 config/web.php),DSN( Data Source Name ...
- YII2数据库操作出现类似Database Exception – yii\db\Exception SQLSTATE
yii2安装后,连接数据库,必须要安装pdo_mysql扩展
- Yii2数据库操作 事务
Yii2 DAO http://blog.csdn.net/hzqghost/article/details/44116039
- Yii2数据库操作再总结
User::find()->all(); 此方法返回所有数据:User::findOne($id); 此方法返回 主键 id=1 的一条数据(举个例子): User::find()->wh ...
- YII2数据库操作出现类似Database Exception – yii\db\Exception SQLSTATE[HY000] [2002] No such file or director
参考文章:https://blog.csdn.net/zqtsx/article/details/41845511 我的系统时Ubuntu18使用上面的方法时发现,没有MySQL.socket,然后谷 ...
- php框架内的数据库操作(微擎,tp,yii2)
微擎数据库操作 关键字 查询 pdo_get pdo_getcolumn pdo_getall pdo_getslice pdo_fetchcolumn pdo_fetchall 示例: array ...
- Yii 2.0 数据库操作总结
1. 概述 操作数据库有2种方式: DAO(data access object),不安全 ORM(onject relational mapping) 2. DAO Yii::app()->d ...
随机推荐
- Java 分页之最简单的算法
分页实现有很多方式,如jQuery自带框架pagination或在java封装一个类pager等. 下写一个简单易懂的分页算法 逻辑: // 步骤1:设置每页页数大小 long pageS ...
- XCode5无法设置Deployment Target的解决办法
今天使用XCode5创建新项目的时候发现无法修改Deployment Target,只能选择iOS7,谷歌了一下找到了答案,在这里分享给大家:) 这是由于XCode5默认会选择在64位的环境下运行,在 ...
- IIS5.1、IIS6.0、IIS7.5中安装配置MVC 3
本文主要介绍在IIS5.1.IIS6.0.IIS7.5中安装配置MVC 3的具体办法! 正文: IIS5.1 1. 安装Microsoft .net FrameWork 4.0安装包; 2. 安装AS ...
- lvs+keepalived+bind实现负载均衡高可用智能dns
整体架构: 1.IP地址规划: Dns1:172.28.0.54 Dns2:172.28.0.55 Dr服务器主:172.28.0.57 Dr服务器从:172.28.0.67 Vip:172.28.0 ...
- eclipse 创建maven web错误Cannot change version of project facet Dynamic web module to 3.1解决方案
Dynamic Web Module 选择“3.1”,java选择“1.8”,报错:Cannot change version of project facet Dynamic web module ...
- LINUX find 实用
查找文件find ./ -type f 查找目录find ./ -type d 查找名字为test的文件或目录find ./ -name test 查找名字符合正则表达式的文件,注意前面的‘.*’(查 ...
- Python基础--通用序列操作
Python 继续 Python包含6种内建的序列,各自是:列表.元组.字符串.Unicode字符串.buffer对象和xrange对象.我们将逐步进行介绍. 今天主要介绍一下通用序列操作.放之四海而 ...
- hdu 4112 Break the Chocolate(乱搞题)
题意:要把一块n*m*k的巧克力分成1*1*1的单元,有两种操作方式:1,用手掰(假设力量无穷大),每次拿起一块,掰成两块小的:2,用刀切(假设刀无限长),可以把多块摆在一起,同时切开.问两种方式各需 ...
- PHP性能:序——谈ab(Apache Bench)压力测试工具
PHP性能:序——谈ab(Apache Bench)压力测试工具 ab(Apache Bench)是啥? ab是Apache自带的一个压力测试软件,可以通过ab命令和选项对某个URL进行压力测试.a ...
- LeakCanary Android 和 Java 内存泄露检测
说起内存泄漏还是挺让人头疼的,而且不是每个手机都会发生的情况,往往又不易察觉,那么今天我们就来介绍下LeakCanary这个工具 githup:https://github.com/square/le ...