yii2的数据库操作

* all():将返回一个由行组成的数组,每一行是一个由名称和值构成的关联数组(译者注:省略键的数组称为索引数组)。

* one():返回结果集的第一行。

* column():返回结果集的第一列。

* scalar():返回结果集的第一行第一列的标量值。第一列第一个

* exists():返回一个表示该查询是否包结果集的值。是否有结果

* count():返回 COUNT 查询的结果。

* max(): 返回某一列的最大值

* min(): 返回某一列的最小值

* createCommand(): 测试query对象 sql params queryall

* indexBy: 以某些字段值为索引(下标)example:indexBy('user_id') function($row){return $row['id'].$row['name']}

  all()方法的优化

use yii\db\ActiveRecord;
use yii\db\Query;
$query = (new Query())->select('product_id,sku')->from('de_product');
$data = [];
foreach ($query->batch(200) as $batch) {//默认一次100条,可以自己设置参数
    $data[] = $batch;
    unset($batch);
}
foreach ($query->each() as $user) {//一次一条
    $data[] = $user;
}
原生查询

* queryAll() 返回多行

* queryOne() 返回第一行

* queryColumn......

* execute 返回执行sql所受到影响的行数

$params = [':image_id'=>20];
$id = 564;
$data = Yii::$app->db->createCommand('SELECT * FROM de_product where product_id=:id')->bindValues($params)->queryAll();
 
$data = Yii::$app->db->createCommand('SELECT * FROM de_product where product_id=:id',$params)->queryAll();
 
$data = Yii::$app->db->createCommand('SELECT * FROM de_product where product_id=:id')->bindParam(':id',$id)->queryAll();
 
$data = Yii::$app->db->createCommand("UPDATE jh_users SET username_ch='超级管理员11' WHERE user_id=1")->execute();
 
$data = Yii::$app->db->createCommand()->insert('jh_images',[
    'image_url'=>'sagasgdsa000'
])->execute();
 
$data = Yii::$app->db->createCommand()->batchInsert('jh_images',['image_url'],[
    ['三国杀1'],
    ['三国杀2']
])->execute();
 
Yii::$app->db->createCommand()->update('user', ['status' => 1], 'age > 30')->execute();
 查询结果转为数组

$data = Users::find()->orderBy('user_id desc')->all();//获取多条
//方法一
$arr = array();
foreach($data as $t)
{
    $arr[] = $t->attributes;
}
//方法二
$arr = array_map(function($record) {
    return $record->attributes;
 }, $data);
//方法三
$arr = ArrayHelper::toArray($data);
//方法四
$arr = Users::find()->asArray()->one();
$users = Users::findOne('111')->attributes;
执行事物

$db = Yii::$app->db;
$transaction = $db->beginTransaction();
try {
    $data = $db->createCommand()->batchInsert('jh_images',['image_url'],[
        ['三国杀7'],
        ['三国杀8']
    ])->execute();
    $data = $db->createCommand("UPDATE jh_users SET username_ch='超级管理员78' WHERE user_id=1")->execute();
    $transaction->commit();
} catch(\Exception $e) {
    $transaction->rollBack();
    throw $e;
} catch(\Throwable $e) {
    $transaction->rollBack();
    throw $e;
}
return $data;
 完整查询

public function getList($table,$field='*',$where=[],$order='',$limit='',$page=''){
    try {
        $lists = (new Query());
        $lists->select($field)->from($table);
        if($where)
            $lists->where($where);
        if($order)
            $lists->orderBy($order);
        if($limit)
            $lists->limit($limit);
        if($page)
            $lists->offset(($page-1)*$limit);
        $lists = $lists->all();
    } catch (\Error $e){
       return ['status'=>'Error','error_msg'=>$e->getMessage()];
    } catch (\Exception $e) {
       return ['status'=>'Exception','error_msg'=>$e->getMessage()];
    } catch (\Throwable $e) {
       return ['status'=>'Throwable','error_msg'=>$e->getMessage()];
    }
     return ['status'=>'successful','data'=>$lists];
}
模型操作

 

class Admin extends \yii\db\ActiveRecord
{
    public static function GetDb()
    {
        return Yii::$app->get('jhhrms');
    }
    
    /**
     * 入库一维数组
     * @param $data
     * @return mixed
     */
    public function add($data){
         $this->setAttributes($data);
         //注意:!!!当setAttributes($attributes,fase);时不用设置rules规则,否则则需要设置字段规则;
         $this->isNewRecord = true;
         $this->save();
         return $this->admin_id;
    }
 
    /**
     * 入库多维数组
     * @param $data
     * @return array
     */
    public function addAll($data){
        $ids = [];
        foreach ($data as $datum) {
            $this->isNewRecord = true;
            $this->setAttributes($datum);
            $this->save() && array_push($ids,$this->admin_id) && $this->admin_id = 0;
        }
        return $ids;
    }
    
    public function rules(){
        return [
          [['username','employee_number'],'required'],
          [['depart_id','position_id','role_id'],'integer'],
        ];
控制器调用模型

$data = [
    [   'username'        => '毛克利',
        'employee_number' => '23431'
    ],
    [   'username'        => '巴克拉',
        'employee_number' => '23432'
    ]
];
 
$model = new Admin();
var_dump($model->addAll($data));
 
//删除
$admin = Admin::find()->where(['admin_id'=>180])->one();
echo $admin->delete();
 
//删除多条
$result = Admin::deleteAll(['employee_number'=>'03252']);
var_dump($result);
 
//修改
$admin =  Admin::find()->where(['username'=>'毛克利'])->one();
$admin->username = '新毛克利';
echo $admin->save();
 
//修改工号为23431的员工的名字为毛克利kk
$res = $model->updateAll(['username'=>'毛克利kk'],['employee_number'=>'23431']);
$res = Yii::$app->db->createCommand()->update('jh_admin', ['username' => '毛克利kk'], 'employee_number = 23431')->execute();
var_dump($res);
 子查询和union查询

//子查询
$subQuery = (new Query())->select('COUNT(*)')->from('customer');
$query = (new Query())->select(['id', 'count' => $subQuery])->from('customer');
//SELECT `id`, (SELECT COUNT(*) FROM `customer`) AS `count` FROM `customer`
 
union查询
$query1 = (new Query())->select('user_id as id,username as name')->from('jh_users')->limit(3);
$query2 = (new Query())->select('per_id as id,per_name as name')->from('jh_performance')->limit(3);
$lists = $query1->union($query2)->all();
return $lists;

你可能感兴趣的:(yii2的数据库操作)