YII2.0 数据库增删改查
/*==================== dkhBaseModel 数据库增删改查方法 start ================================*/
//新增一条数据
public function baseInsertData($data){
if(!is_array($data)) {return $this->setError(['errmsg'=>'data Error']);};
$db = \Yii::$app->db;
$ok = $db->createCommand()->insert($this->tableName(), $data)->execute();
if($ok){
//返回自增id
return $db->getLastInsertID();
}else{
return $this->setError(['errmsg'=>'插入记录失败']);
}
} //通过条件查询一条记录
public function baseGetOne($condition = [],$orderBy = 'id DESC',$select = array()){
//$condition 搜索条件 如:$condition = ['and'];$condition[] = ['=','id',1];$condition[] = ['LIKE','name','dkh'];
//$select 字段过滤 如: ['id','field1','field2']
return $this->find()->select($select)->where($condition)->orderBy($orderBy)->asArray()->one();
} //通过条件查询一条关联模型记录
public function baseGetOneRelation($condition = [],$tables,$orderBy = '',$select = array()){
return $this->find()->joinWith($tables)->select($select)->where($condition)->orderBy($orderBy)->asArray()->one();
} //获取全部数据
public function baseGetAll($condition = [],$orderBy = 'id DESC',$select = array()){
return $this->find()->select($select)->where($condition)->orderBy($orderBy)->asArray()->all();
} //通过条件查询多条关联模型记录
public function baseGetAllRelation($condition = [],$tables,$orderBy = '',$select = array()){
return $this->find()->joinWith($tables)->select($select)->where($condition)->orderBy($orderBy)->asArray()->all();
} //根据id删除一条数据
public function baseDeleteById($id){
$this->id = $id;
return $this->findOne($id)->delete(); } //删除指定条件的数据
public function baseDeleteAll($condition = []){
if(empty($condition)) {return $this->setError(['errmsg'=>'deleteAll Error']);};
return $this->deleteAll($condition);
} //执行原生sql语句,一般用于更新,批量新增,删除数据
public function baseExecuteSql($sql){
$db = \Yii::$app->db;
//在调用的地方做执行是否成功的判断
return $db->createCommand($sql)->execute();
} //执行原生sql语句,一般用于查询数据 返回单行
public function baseQueryOneSql($sql){
$db = \Yii::$app->db;
return $db->createCommand($sql)->queryOne();
} //执行原生sql语句,一般用于查询数据 返回多行
public function baseQueryAllSql($sql){
$db = \Yii::$app->db;
return $db->createCommand($sql)->queryAll();
} //通过主键查询一条记录
public function baseGetOneByid($id){
$model = $this->findOne($id);
if($model){
return $model->attributes;
}else{
return array();
}
} //更新符合条件的数据
public function baseUpdateData($data,$condition = []){
if(empty($condition)) {return $this->setError(['errmsg'=>'condition Empty']);};
$res = $this->updateAll($data,$condition);
if($res === false){
return $this->setError(['errmsg'=>'更新失败']);
}
return $res;
} //获取分页数据
public function basePageData($condition = [],$page,$pageSize,$orderBy = 'id DESC',$select = array()){
//$page,$pageSize 相当于 LIMIT $page,$pageSize
//$select 过滤字段 ['id','field1','field2']
return $this->find()->select($select)->where($condition)->offset($page)->limit($pageSize)->orderBy($orderBy)->asArray()->all();
} //获取分页数据 并且 关联模型记录
public function basePageDataRelation($condition = [],$page,$pageSize,$tables,$orderBy = '',$select = array()){
//$page,$pageSize 相当于SQL语句 LIMIT $page,$pageSize
//$select 字段过滤 如: ['id','field1','field2']
//$tables 关联模型表 如: ['table1','table2']
return $this->find()->joinWith($tables)->select($select)->where($condition)->orderBy($orderBy)->offset($page)->limit($pageSize)->asArray()->all();
} //通过条件查询记录条数
public function baseGetCount($condition = [],$select = array()){
return $this->find()->select($select)->where($condition)->count();
} //通过条件查询记录条数 并且 关联模型
public function baseGetCountRelation($condition = [],$tables,$select = array()){
return $this->find()->joinWith($tables)->select($select)->where($condition)->count();
} //通过条件查询一条记录
public function baseModelGetOne($params){
if(isset($params['condition']) && is_array($params['condition']) && !empty($params['condition'])){
$condition = $params['condition'];
}else{
$condition = [];
}
if(isset($params['field']) && is_array($params['field']) && !empty($params['field'])){
$field = $params['field'];
}else{
$field = [];
}
if(isset($params['order']) && !empty($params['order'])){
$order = $params['order'];
}else{
$order = 'id DESC';
}
return $this->find()->select($field)->where($condition)->orderBy($order)->asArray()->one();
} //通过条件查询一条关联模型记录
public function baseModelGetOneRelation($params){
if(isset($params['condition']) && is_array($params['condition']) && !empty($params['condition'])){
$condition = $params['condition'];
}else{
$condition = [];
}
if(isset($params['field']) && is_array($params['field']) && !empty($params['field'])){
$field = $params['field'];
}else{
$field = [];
}
if(isset($params['order']) && !empty($params['order'])){
$order = $params['order'];
}else{
$order = 'id DESC';
}
if(isset($params['join']) && is_array($params['join']) && !empty($params['join'])){
$join = $params['join'];
}else{
$join = '';
}
return $this->find()->joinWith($join)->select($field)->where($condition)->orderBy($order)->asArray()->one();
} //获取全部数据
public function baseModelGetAll($params){
if(isset($params['condition']) && is_array($params['condition']) && !empty($params['condition'])){
$condition = $params['condition'];
}else{
$condition = [];
}
if(isset($params['field']) && is_array($params['field']) && !empty($params['field'])){
$field = $params['field'];
}else{
$field = [];
}
if(isset($params['order']) && !empty($params['order'])){
$order = $params['order'];
}else{
$order = 'id DESC';
}
return $this->find()->select($field)->where($condition)->orderBy($order)->asArray()->all();
} //通过条件查询多条关联模型记录
public function baseModelGetAllRelation($params){
if(isset($params['condition']) && is_array($params['condition']) && !empty($params['condition'])){
$condition = $params['condition'];
}else{
$condition = [];
}
if(isset($params['field']) && is_array($params['field']) && !empty($params['field'])){
$field = $params['field'];
}else{
$field = [];
}
if(isset($params['order']) && !empty($params['order'])){
$order = $params['order'];
}else{
$order = 'id DESC';
}
if(isset($params['join']) && is_array($params['join']) && !empty($params['join'])){
$join = $params['join'];
}else{
$join = '';
}
return $this->find()->joinWith($join)->select($field)->where($condition)->orderBy($order)->asArray()->all();
} //获取分页数据
public function baseModelPageData($params){
if(isset($params['condition']) && is_array($params['condition']) && !empty($params['condition'])){
$condition = $params['condition'];
}else{
$condition = [];
}
if(isset($params['field']) && is_array($params['field']) && !empty($params['field'])){
$field = $params['field'];
}else{
$field = [];
}
if(isset($params['order']) && !empty($params['order'])){
$order = $params['order'];
}else{
$order = 'id DESC';
}
if(isset($params['page'])){
$page = $params['page'];
}else{
$page = 0;
}
if(isset($params['pageSize'])){
$pageSize = $params['pageSize'];
}else{
$pageSize = 10;
}
return $this->find()->select($field)->where($condition)->offset($page)->limit($pageSize)->orderBy($order)->asArray()->all();
} //获取分页数据 并且 关联模型记录
public function baseModelPageDataRelation($params){
if(isset($params['condition']) && is_array($params['condition']) && !empty($params['condition'])){
$condition = $params['condition'];
}else{
$condition = [];
}
if(isset($params['field']) && is_array($params['field']) && !empty($params['field'])){
$field = $params['field'];
}else{
$field = [];
}
if(isset($params['order']) && !empty($params['order'])){
$order = $params['order'];
}else{
$order = 'id DESC';
}
if(isset($params['join']) && is_array($params['join']) && !empty($params['join'])){
$join = $params['join'];
}else{
$join = '';
}
if(isset($params['page'])){
$page = $params['page'];
}else{
$page = 0;
}
if(isset($params['pageSize'])){
$pageSize = $params['pageSize'];
}else{
$pageSize = 10;
}
return $this->find()->joinWith($join)->select($field)->where($condition)->orderBy($order)->offset($page)->limit($pageSize)->asArray()->all();
} //通过条件查询记录条数
public function baseModelGetCount($params){
if(isset($params['condition']) && is_array($params['condition']) && !empty($params['condition'])){
$condition = $params['condition'];
}else{
$condition = [];
}
if(isset($params['field']) && is_array($params['field']) && !empty($params['field'])){
$field = $params['field'];
}else{
$field = [];
}
return $this->find()->select($field)->where($condition)->count();
} //通过条件查询记录条数 并且 关联模型
public function baseModelGetCountRelation($params){
if(isset($params['condition']) && is_array($params['condition']) && !empty($params['condition'])){
$condition = $params['condition'];
}else{
$condition = [];
}
if(isset($params['field']) && is_array($params['field']) && !empty($params['field'])){
$field = $params['field'];
}else{
$field = [];
}
if(isset($params['join']) && is_array($params['join']) && !empty($params['join'])){
$join = $params['join'];
}else{
$join = '';
}
return $this->find()->joinWith($join)->select($field)->where($condition)->count();
} //删除指定条件的数据
public function baseModelDeleteAll($params){
if(empty($params['condition'])) {return $this->setError(['errmsg'=>'deleteAll Error']);};
return $this->deleteAll($params['condition']);
} //更新符合条件的数据
public function baseModelUpdateData($params){
if(empty($params['condition'])) {return $this->setError(['errmsg'=>'condition is Empty']);};
$res = $this->updateAll($params['data'],$params['condition']);
if($res === false){
return $this->setError(['errmsg'=>'更新失败']);
}
return $res;
}
增删改查使用方法:
//选择分组
$condition = ['and'];
$condition[] = ['=','member.shop_id',$params['shop_id']];
$condition[] = ['IN','member.member_group_id',$params['member_tag']['groups']]; //索引数组
$wshMemberModel = new WshMember();
$memberList = $wshMemberModel->baseGetAllRelation($condition,['wxUserInfos'],'member.id DESC',['member.id']);
$wshWxUsersModel = new WshWxUsers();
$userList = $wshWxUsersModel->baseGetAll(['shop_id'=>$params['shop_id'],'user_id'=>$uid],'id DESC',['user_id','open_id']);
$insertData = [
'material_id'=>isset($params['material_id'])?$params['material_id']:0,
'shop_id'=>$params['shop_id'],
'shop_sub_id'=>$_SESSION['_staff']['shop_sub_id'],
'send_time'=>$now,
'send_type'=>$params['send_type'],
'text_content'=>$params['text_content'],
'sort_content'=>$params['sort_content'],
]; $insertId = $wshWxMessageSendMutilModel->baseInsertData($insertData);
$dkhWxMessageMemberMutilModel = new DkhWxMessageMemberMutil();
$successValues = '';$successSql = '';
//组装sql语句
foreach($successList as $item){
$successValues .= "('{$insertId}','{$item['user_id']}','1','{$now}','{$now}'),";
}
if(!empty($successValues)) {
$successSql = "INSERT INTO `dkh_wx_message_member_mutil` (`send_id`,`user_id`,`send_result`,`created`,`modified`) VALUES " . substr($successValues, 0, -1) . ';';
//插入发送成功数据
$dkhWxMessageMemberMutilModel->baseExecuteSql($successSql);
}
//消费减余额
$balance = $balanceData['balance'] - $data['balance'];
$map = ['and'];
$map[] = ['=', 'member_id', $orderData['member_id']];
$map[] = ['>=', 'balance', $data['balance']];
$balanceOk = $dkhMemberExtendModel->baseUpdateData(['balance' => $balance], $map);
//首充 ,可参加充值赠送活动
$condition = ['and'];
$condition[] = ['=', 'dkh_recharge_activity.shop_id', $data['shop_id']];
$condition[] = ['=', 'dkh_recharge_activity.is_del', 0];
$condition[] = ['=', 'dkh_recharge_activity.status', 1];
$condition[] = ['<=', 'dkh_recharge_activity.start_time', $now];
$condition[] = ['>=', 'dkh_recharge_activity.end_time', $now];
$dkhRechargeActivity = new DkhRechargeActivity();
$rechargeActivityData = $dkhRechargeActivity->baseGetOneRelation($condition, ['dkhRechargeActivityRelation'], 'dkh_recharge_activity.id DESC');
Yii2查询之where条件拼装
熟悉Yii2的查询条件后,用Active Record查询数据非常方便。
以下我们介绍where()方法当中,条件的拼装方式。 #某个值为null,会用IS NULL来生成语句:
['type' => 1, 'status' => 2] // 生成:(type = 1) AND (status = 2)
['id' => [1, 2, 3], 'status' => 2] // 生成:(id IN (1, 2, 3)) AND (status = 2)
['status' => null] // 生成:status IS NULL
['NOT', ['type' => null]] // 生成:type IS NOT NULL #对比
['>', 'id', 1] // 生成:id > 1
['<', 'id', 100] // 生成:id < 100
['=', 'id', 10] // 生成:id = 10
['>=', 'id', 1] // 生成:id >= 1
['<=', 'id', 100] // 生成:id <= 100
['!=', 'id', 10] // 生成:id != 10 ['and', 'id' => 1, 'id' => 2] // 生成:id=1 AND id=2
['and', 'id=1', 'id=2'] // 生成:id=1 AND id=2
['and', 'type=1', ['or', 'id=1', 'id=2']] // 生成:type=1 AND (id=1 OR id=2) ['or', ['type' => [7, 8, 9]], ['id' => [1, 2, 3]]] // 生成:(type IN (7, 8, 9) OR (id IN (1, 2, 3))) ['not', ['attribute' => null]] // 生成:NOT (attribute IS NULL) ['between', 'id', 1, 10] // 生成:id BETWEEN 1 AND 10
['not between', 'id', 1, 10] // 生成:id NOT BETWEEN 1 AND 10 ['in', 'id', [1, 2, 3]] // 生成:id IN (1, 2, 3)
['id' => [4, 8, 15]] // 生成:id IN (4, 8, 15)
['not in', 'id', [1, 2, 3]] // 生成:id NOT IN (1, 2, 3) ['in', ['id', 'name'], [['id' => 1, 'name' => 'foo'], ['id' => 2, 'name' => 'bar']]] // 生成:(`id`, `name`) IN ((1, 'foo'), (2, 'bar')) #用子查询作为IN条件的值,如下:
['in', 'user_id', (new Query())->select('id')->from('users')->where(['active' => 1])] ['like', 'name', 'tester'] // 生成:name LIKE '%tester%'
['like', 'name', ['test', 'sample']] // 生成:name LIKE '%test%' AND name LIKE '%sample%'
['like', 'name', '%tester', false] // 生成:name LIKE '%tester'
// 这是自定义查询方式,要传入值为false的运算数3,并且自行添加%
['or like', 'name', ['test', 'sample']] // 生成:name LIKE '%test%' OR name LIKE '%sample%'
['not like', 'name', 'tester'] // 生成:name NOT LIKE '%tester%'
['or not like', 'name', ['test', 'sample']] // 生成:name NOT LIKE '%test%' OR name NOT LIKE '%sample%' ['exists', (new Query())->select('id')->from('users')->where(['active' => 1])] // 生成:EXISTS (SELECT "id" FROM "users" WHERE "active"=1)
YII2.0 数据库增删改查的更多相关文章
- Yii2框架数据库增删改查小结
User::find()->all(); //返回所有用户数据:User::findOne($id); //返回 主键 id=1 的一条数据: User::find()->wh ...
- Yii2.0高级框架数据库增删改查的一些操作(转)
yii2.0框架是PHP开发的一个比较高效率的框架,集合了作者的大量心血,下面通过用户为例给大家详解yii2.0高级框架数据库增删改查的一些操作 --------------------------- ...
- Yii2.0高级框架数据库增删改查的一些操作
yii2.0框架是PHP开发的一个比较高效率的框架,集合了作者的大量心血,下面通过用户为例给大家详解yii2.0高级框架数据库增删改查的一些操作 --------------------------- ...
- go——beego的数据库增删改查
一直都不理解使用go语言的时候,为什么还要自己去装beego,以为使用go便可以解决所有的问题,结果在朋友的点拨下,才意识到: go与beego的关系就好比是nodejs与thinkjs的关系,因此也 ...
- (转)SQLite数据库增删改查操作
原文:http://www.cnblogs.com/linjiqin/archive/2011/05/26/2059182.html SQLite数据库增删改查操作 一.使用嵌入式关系型SQLite数 ...
- WindowsPhone8 数据库增删改查
今天第一次在博客园发表文章,如果有的地方写的不对,还请大家指出! 1.这就是一个简单wp8数据库增删改查 1.创建数据表Person [Table] public class Person : INo ...
- Android(java)学习笔记193:利用谷歌API对数据库增删改查(推荐使用)
接下来我们通过项目案例来介绍:这个利用谷歌API对数据库增删改查 1.首先项目图: 2.这里的布局文件activity_main.xml: <LinearLayout xmlns:android ...
- ThinkPHP 的模型使用对数据库增删改查(五)
原文:ThinkPHP 的模型使用对数据库增删改查(五) ThinkPHP 的模型使用 // 直接连接数据库,但是得先去配置文件中配置下才行 class IndexAction extends Act ...
- Android SQLite 数据库 增删改查操作
Android SQLite 数据库 增删改查操作 转载▼ 一.使用嵌入式关系型SQLite数据库存储数据 在Android平台上,集成了一个嵌入式关系型数据库--SQLite,SQLite3支持NU ...
随机推荐
- C#新功能--命名参数与可选参数
C#新功能--命名参数与可选参数 可能是篇幅太短了,又被打入冷宫了.先重发一篇加上可选参数.本来不想加这个呢,因为可选参数可能大家用的会多点.其实这 两个在VB中早就有了,在C#中,只有在.net4以 ...
- 挖一下插件v1.5版本发布
Chrome图片下载插件,支持网页截屏 v.1.5更新说明: 1.增加下载图片按日期分类保存选项,便于管理,用户可根据需要开启/关闭此设置 2.增加网页图片采集快捷键: (1)采集页面图片(Ctrl+ ...
- 可供VC调用的QT编写的界面DLL方法
一般直接编写的QT动态库是无法被Windows下的VC6.0等调用的. 如下步骤 第一步:必须要在QT界面库源码下包含qtwinmigrate的源码包和库,网上可下载到. 第二步:在QT的proc文件 ...
- Java自带的性能监测工具用法简介——jstack、jconsole、jinfo、jmap、jdb、jsta、jvisualvm
JDK内置工具使用 一.javah命令(C Header and Stub File Generator) 二.jps命令(Java Virtual Machine Process Status To ...
- Python中的多进程与多线程(二)
在上一章中,学习了Python多进程编程的一些基本方法:使用跨平台多进程模块multiprocessing提供的Process.Pool.Queue.Lock.Pipe等类,实现子进程创建.进程池(批 ...
- 结构-行为-样式-Javascript 深度克隆函数(转)
突然想到有一回面试的时候有一个问题一直挂在心头,于是乎在网上找了找,这个比较好: //深度克隆 function deepClone(obj) { var result, oClass = isCla ...
- Linux中top和free命令详解(转)
top:命令提供了实时的对系统处理器的状态监视.它将显示系统中CPU最"敏感"的任务列表. 该命令可以按CPU使用.内存使用和执行时间对任务进行排序: 而且该命令的很多特性都可以通 ...
- configure HDFS(hadoop 分布式文件系统) high available
注:来自尚学堂小陈老师上课笔记 1.安装启动zookeeper a)上传解压zookeeper包 b)cp zoo_sample.cfg zoo.cfg修改zoo.cfg文件 c)dataDir=/o ...
- 前端之Photoshop切片
什么是切片 ? (Photoshop中的切片) 切片:将图片切成几部分,一片一片往上传,这样上传的速度比较快.每个切片作为一个独立的文件传输,文件中包含切片自己的设置.颜色调板.链接.翻转效果 ...
- Arch安装KDE5
plasma desktop Install the plasma-meta meta-package or the plasma group. Alternatively, for a more m ...