1.添加数据

如下,使用insert方法:t_admin_user为数据表名。。其他的是属性。。

$num = Yii::$app->db->createCommand()->insert('t_admin_user', [
'username' => $this->username,
'origin_pwd' => trim($info['password']),
'password' => $this->passwordHash($info['password']),
'roleid' => $this->roleid,
'role' => $this->role,
'ctime' => $this->ctime,
'salt' => $this->salt,
'status' => $this->status,
])->execute();

2.修改数据

如下,使用update方法:t_admin_use为数据表名,'origin_pwd' =>$origin_pwd,'password'=>$password,'salt'=>$salt是要修改的属性,'uid = '.$uid是条件。

 $modNum = Yii::$app->db->createCommand()->update('t_admin_user', ['origin_pwd' =>$origin_pwd,'password'=>$password,'salt'=>$salt], 'uid = '.$uid)->execute();

3.批量添加

如下,Message为数据表名。

 if($userInfo){
foreach($userInfo as $v){
$rows[] = array(
'uid' => trim($v['uid']),
'content' => trim($info['content']),
'type' => trim($info['type']),
'create_time' => $time,
'update_time' => $time,
'status' => 0
);
} return Yii::$app->db->createCommand()->batchInsert(Message::tableName(), ['uid', 'content','type','create_time','update_time','status'], $rows)->execute();
}

4.批量修改

如下,Message为数据表,'create_time'=>trim($info['create_time'])是条件。。

$model = new Message();
$result = $model->updateAll(['content'=>trim($info['content']),'update_time'=>time()],['create_time'=>trim($info['create_time'])]);

5.插入数据成功后,新增的id

$post->save();
//得到上次插入的Insert id
$id = $post->attributes['id'];
如此很简单

例子:

 public function doGetCreateSalesInfo($info){
$this->name = trim($info['name']);
$this->company_id = 58;
$this->ctime = date('Y-m-d H:i:s',time());
$this->password = md5(trim($info['password']));
$this->phone = trim($info['phone']);
$this->email = trim($info['email']);
$this->admin_id = trim($info['admin_id']);
if($this->save()){
$id = $this->attributes['id'];
$model = self::find()->where(['id'=>$id])->one();
$model->code = 'BLM'.sprintf("%07d",$id);
if($model->save()){
return 1;
}else{
return -1;
}
}
}

6.查找数据信息

    $goodsTypes = Yii::app()->getDb()->createCommand()
->select('type_id, type_name')
->from('goods_type')
->where('status=1')->queryAll();

7.连表查询

$goods = Yii::app()->getDb()->createCommand()->from('goods g')
        ->select('g.good_id, g.good_name, gt.type_name, g.price, g.buy_nums, g.commit_nums, g.create_time')
        ->join('goods_type gt', 'g.good_type=gt.type_id')
        ->where('g.`status`=1 and gt.`status`=1')
        ->order('g.create_time desc')
        ->queryAll();

8.删除

$row = Yii::app()->getDb()->createCommand()
        ->delete('goods', "good_id=:good_id", array(
            ':good_id' => $goods_id,
        ));
05-11 20:13