Yii2连接数据库
1 2 3 4 5 6 7
| return [ 'class' => 'yii\db\Connection', 'dsn' => 'mysql:host=localhost;dbname=basic', 'username' => 'root', 'password' => '123456', 'charset' => 'utf8', ];
|
接下来的所有操作都是基于yii\db\Query 构造器的方法
添加数据
数据添加
批量添加
删除数据
在这里就不演示删除了,小编一般都是使用软删除,就是更改站在数据库中设置一个字段作为删除的条件
1
| $this->addColumn('表名字','is_delete', $this->string(11)->notNull()->defaultValue('N')->comment('是否删除:Y:删除 ;N:不删除'));
|
在这里设置默认值为N,删除的时候通过ID更改这条数据的字段就可以了,超级简单,Yii的修改语句在下方展示。
更改数据
数据更改
1 2 3 4 5 6 7 8 9 10 11 12
| public function user_status(): void { $model = EmployeeInterViewProblemDo::findOne($value['id']); if ($model === null) { throw new Exception('信息不存在'); } $model->attributes = $value; $model->read_status = 'read'; if (!$model->save()) { throw new ValidateException($model); } }
|
批量更改
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| public function confirmReply(array $params) { if (empty($params['record'])) { throw new Exception('请输入回复信息'); } $model = EmployeeInterViewProblemDo::find()->select('id')->where(['in','id', $params['id']])->count(); if (count($params['id']) !== (int)$model) { throw new Exception('信息不存在'); }
$data = [ 'record' => $params['record'], 'status' => 'Y', 'record_by' => Yii::$app->session['LoginInfo']['name'], 'create_at' => time() ];
$updateProblem = (new EmployeeInterViewProblemDo)::updateAll($data, ['id'=> $params['id']]); if (!$updateProblem) { throw new ValidateException($model); }
}
|
查询数据
返回查询数据
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| $query = EmployeeInterViewDo::find();
$query->select('s.id, s.problem, s.record, s.record_by, s.status, s.create_at, m.interview_at'); $query->from(['m' => EmployeeInterViewDo::tableName()]);
$query->join('LEFT JOIN', ['s' => EmployeeInterViewProblemDo::tableName()], 's.interview_id = m.id'); $query->Where(['s.name' => 'Yes']); $query->andWhere(['s.status' => 'Y']); $query->andWhere(['in', 'id', $params['id']]);
$pageNum = $params['pageNum'] ?? 1; $numPerPage = $params['numPerPage'] ?? 20;
$this->pageArr = [ 'count' => $query->count(), 'currentPage' => $pageNum, 'pageSize' => $numPerPage, 'pageNumShown' => 10, ];
$this->list = $query ->orderBy(['m.create_at' => SORT_DESC]) ->limit((int)$numPerPage) ->offset(($pageNum - 1) * $numPerPage) ->asArray() ->all();
|
查询数据库,倘若查不到返回空
1 2 3 4 5 6 7 8 9 10
| public function getstatus(array $params, $status) { $query = EmployeeInterViewProblemDo::find() ->where(['in', 'id', $params]) ->andWhere(['status' => $status]) ->exists(); if (!empty($query)) { $this->apiReturn('300', '该状态不可进行该操作'); } }
|
此外,yii\db\Query 提供了一套用于不同查询目的的方法:
- all() ———– 返回一个由行组成的数组,每一行是一个由名称和值构成的关联数组
- one() ———– 返回结果集的第一行
- column() ———– 返回结果集的第一列
- scalar() ———– 返回结果集的第一行第一列的标量值
- exists() ———– 返回一个表示该查询是否包含结果集的值
- count() ———– 返回 COUNT 查询的结果
- sum() ———– 返回指定列的和值
- average() ———– 返回指定列的平均值
- max() ———– 返回指定列的最大值
- min() ———– 返回指定列的最小值
事物处理