-------------------------------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.getyii.com/topic/219

Yii2数据库操作的各种写法的更多相关文章

  1. Yii2 数据库操作汇总

    对象操作 查询 //1.简单查询 $admin=Admin::model()->findAll($condition,$params); $admin=Admin::model()->fi ...

  2. yii2 数据库操作(转)

    开始使用数据库首先需要配置数据库连接组件,通过添加 db 组件到应用配置实现("基础的" Web 应用是 config/web.php),DSN( Data Source Name ...

  3. yii2 数据库操作详解(转载)

    开始使用数据库首先需要配置数据库连接组件,通过添加 db 组件到应用配置实现("基础的" Web 应用是 config/web.php),DSN( Data Source Name ...

  4. YII2数据库操作出现类似Database Exception – yii\db\Exception SQLSTATE

    yii2安装后,连接数据库,必须要安装pdo_mysql扩展

  5. Yii2数据库操作 事务

    Yii2 DAO http://blog.csdn.net/hzqghost/article/details/44116039

  6. Yii2数据库操作再总结

    User::find()->all(); 此方法返回所有数据:User::findOne($id); 此方法返回 主键 id=1 的一条数据(举个例子): User::find()->wh ...

  7. 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,然后谷 ...

  8. php框架内的数据库操作(微擎,tp,yii2)

    微擎数据库操作 关键字 查询 pdo_get pdo_getcolumn pdo_getall pdo_getslice pdo_fetchcolumn pdo_fetchall 示例: array ...

  9. Yii 2.0 数据库操作总结

    1. 概述 操作数据库有2种方式: DAO(data access object),不安全 ORM(onject relational mapping) 2. DAO Yii::app()->d ...

随机推荐

  1. linux系统下使用apt-get install 方法安装lamp环境

    1.更新源,获得最近的软件包的列表,列表中包含一些包的信息,比如这个包是否更新过. sudo apt-get update 2.更新系统中已安装的软件包 sudo apt-get upgrade 3. ...

  2. 12个高效的VS调试技巧

    介绍 调试是软件开发周期中的一个很重要的部分,有时很有挑战性,有时候则让程序员迷惑,有时候让程序员发疯,但是.可以肯定的是,对于任何不是太那个微不足道的程序来说,调试是不可避免的.近年来,调试工具的发 ...

  3. 将Latex tex文档转换成 word文档(下)

    在上篇中我们介绍了一款将 tex 文件转换成 word 文件的工具 借用万能的搜索引擎,在 Google 上找到了更好的工具 它就是Pandoc 介绍 Pandoc 是由 John McaFarlan ...

  4. YUV图像合成原理

    http://blog.csdn.net/zwz1984/article/details/50403150 http://zhongcong386.blog.163.com/blog/static/1 ...

  5. 自动清理DataGuard备机日志

    >> from zhuhaiqing.info #!/usr/bin/bash #删除DataGuard备机归档日志备份 export ORACLE_HOME=/opt/oracle/pr ...

  6. HTML5 2D平台游戏开发#6地图绘制

    此前已经完成了一部分角色的动作,现在还缺少可以交互的地图让游戏看起来能玩.不过在开始之前应当考虑清楚使用什么类型的地图,就2D平台游戏来说,一般有两种类型的地图,Tile-based和Art-base ...

  7. 机器学习5—logistic回归学习笔记

    机器学习实战之logistic回归 test5.py #-*- coding:utf-8 import sys sys.path.append("logRegres.py") fr ...

  8. CIA 读书笔记

    对此书的评价只有八个字:粗制滥造,到处粘贴. 对于通过表情识别人情绪的教程,最好要有图,图很重要,也最好有案例.

  9. excel表格系列

    MicroSoft Excel表格系列问题 1.excel表格修改默认行高 2.[Excel技巧]Excel实现部分保护技巧

  10. linux vmware提示:此虚拟机似乎正在使用中,取得该虚拟机的所有权失败错误

    用vm的时候,没有挂起和关闭虚拟机,直接关实体机.然后不幸的就异常了. 然后今天用的时候提示 此虚拟机似乎正在使用中. 如果此虚拟机已在使用中,请按“取消”按钮,以免损坏它.如果此虚拟机未使用,请按“ ...