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 ...
随机推荐
- Unix环境部署
http://www.cnblogs.com/chuyuhuashi/p/4423699.html 分布式javahttp://www.cnblogs.com/tangyanbo/p/4499485. ...
- vuex mapActions
在组件中使用 this.$store.dispatch('xxx') 分发 action,或者使用 mapActions 辅助函数将组件的 methods 映射为 store.dispatch 调用( ...
- tail -f 不断刷新
查看log tail -f 会将其不断刷新显示
- linux程序设计——取消一个线程(第十二章)
12.7 取消一个线程 有时,想让一个线程能够要求还有一个线程终止,就像给它发送一个信号一样. 线程有方法能够做到这一点,与与信号处理一样.线程能够被要求终止时改变其行为. pthread_ca ...
- 【Lucene】Apache Lucene全文检索引擎架构之搜索功能3
上一节主要总结了一下Lucene是如何构建索引的,这一节简单总结一下Lucene中的搜索功能.主要分为几个部分,对特定项的搜索:查询表达式QueryParser的使用:指定数字范围内搜索:指定字符串开 ...
- ajax读取文件内容
读取json文件 $.ajax({ url: 'manifest.webapp', type: 'GET', dataType: 'json',//类型不对会出错 timeout: 1000, //设 ...
- C#中的里氏替换原则
里氏转换原则 子类可以赋值给父类对象 父类对象可以强制转化为对应的子类对象 里氏替换原则直观理解就是"子类是父类",反过来就说不通了. 就像男人是人对的,但人是男人就不对了. 这样 ...
- java之UDP(datagramsocket,datagramPacket)实例
import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import ...
- Java基础IO流
流 流的本质是数据传输,根据数据传输特性将流抽象为各种类,方便更直观的进行数据操作.IO流最终要以对象来体现,对象都存在IO包中. IO流的分类 根据处理数据类型的不同分为:字符流和字节流 根据数据流 ...
- git设置全局和单个仓库账号和密码
Git全局配置和单个仓库的用户名邮箱配置 配置全局仓库的账号和密码 git config --global user.name "userName" //你的用户名 git con ...