yii2增删改查


http://www.yiichina.com/tutorial/996
http://www.yiichina.com/tutorial/834
https://www.jianshu.com/p/e89e9580fc67


$db=Yii::$app->db->createCommand(); 


$db->insert()->execute();
$db->batchInsert()->execute();
$db->delete()->execute();
$db->update()->execute();

(new \yii\db\Query())->find()
$StudentModel->find()
Student::find()
select()->all()/one()/each(100);



增
//普通插入
$user= new User;         
$user->username =$username;  
$user->password =$password;  
$user->save()

Yii::$app->db->createCommand()->insert('user', [  
    'name' => 'test',  
    'age' => 30,  
])->execute();



// 批量插入数据
Yii::$app->db->createCommand()->batchInsert('user', ['name', 'age'], [  
    ['test01', 30],  
    ['test02', 20],  
    ['test03', 25],  
])->execute();

Yii::$app->db->createCommand()->batchInsert(UserModel::tableName(), ['user_id','username'], [
    ['1','test1'],
    ['2','test2'],
    ['3','test3'],   
])->execute();



删
User::findOne($id)->delete();

$user = User::find()->where(['name' => 'test'])->one()->delete();

Yii::$app->db->createCommand()
->delete('{{%user}}', 'user_id=:user_id', [':user_id' => $this->id])
   ->execute();

Yii::$app->db->createCommand()
->delete('{{%user}}', "user_id in($userIds) AND parent_id in($parentIds)")->execute();

User::find()->where(['name' => 'test'])->one()->delete();

User::deleteAll(['age'=>'30']);

Yii::$app->db->createCommand()
->delete('{{%user}}', 'user_id=:user_id', [':user_id' => $this->id])->execute();

Yii::$app->db->createCommand()
->delete('{{%user}}', "user_id in($userIds) AND parent_id in($parentIds)")->execute();



改
$user = User::find()->where(['name'=>'test'])->one();
$user->age = 40; //修改age属性值
$user->save();   //保存

// 直接修改:修改用户test的年龄为40
$result = User::model()->updateAll(['age'=>40],['name'=>'test']);

// 使用createCommand()修改
Yii::$app->db->createCommand()->update('user', ['age' => 40], 'name = test')->execute();


//runValidation boolen 是否通过validate()校验字段 默认为true。attributeNames array 需要更新的字段 
$model->update($runValidation , $attributeNames);  

Customer::updateAll(['status' => 1], 'status = 2'); 

Customer::updateAll(['status' => 1], ['status'=> '2','uid'=>'1']);


// 修改username
$user = User::findOne(1);
$user->username = test;
$user->save();

// grade3 累加1
$db->createCommand()->update('yii_users', [
    'grade3' => $grade3 + 1
], 'user_id=:id', [':id' => $parentId])->execute();

// team_num 累加1
UserStats::updateAll(['team_num' => new Expression("team_num + 1")], ['in', 'user_id', $parentIds]);



查
简单查询
one/all/count/sum/average/min/max/scalar/column/exists/where/with/indexBy/asArray
Customer::find()->one();    此方法返回一条数据;
Customer::find()->all();    此方法返回所有数据;
Customer::find()->count();    此方法返回记录的数量;
Customer::find()->average();    此方法返回指定列的平均值;
Customer::find()->min();    此方法返回指定列的最小值 ;
Customer::find()->max();    此方法返回指定列的最大值 ;
Customer::find()->scalar();    此方法返回值的第一行第一列的查询结果;
Customer::find()->column();    此方法返回查询结果中的第一列的值;
Customer::find()->exists();    此方法返回一个值指示是否包含查询结果的数据行;
Customer::find()->asArray()->one();    以数组形式返回一条数据;
Customer::find()->asArray()->all();    以数组形式返回所有数据;
Customer::find()->where($condition)->asArray()->one();    根据条件以数组形式返回一条数据;
Customer::find()->where($condition)->asArray()->all();    根据条件以数组形式返回所有数据;
Customer::find()->where($condition)->asArray()->orderBy('id DESC')->all();    根据条件以数组形式返回所有数据,并根据ID倒序;

关联查询
hasOne/hasMany:返回对应关系的1条/多条记录
//客户表Model:CustomerModel 
//订单表Model:OrdersModel
//国家表Model:CountrysModel
//首先要建立表与表之间的关系 
//在CustomerModel中添加与订单的关系

Class CustomerModel extends yiidbActiveRecord
{
    ...

    public function getOrders()
    {
        //客户和订单是一对多的关系所以用hasMany
        //此处OrdersModel在CustomerModel顶部别忘了加对应的命名空间
        //id对应的是OrdersModel的id字段,order_id对应CustomerModel的order_id字段
        return $this->hasMany(OrdersModel::className(), ['id'=>'order_id']);
    }

    public function getCountry()
    {
        //客户和国家是一对一的关系所以用hasOne
        return $this->hasOne(CountrysModel::className(), ['id'=>'Country_id']);
    }
    ....
}

// 查询客户与他们的订单和国家
CustomerModel::find()->with('orders', 'country')->all();

// 查询客户与他们的订单和订单的发货地址
CustomerModel::find()->with('orders.address')->all();

// 查询客户与他们的国家和状态为1的订单
CustomerModel::find()->with([
    'orders' => function ($query) {
        $query->andWhere('status = 1');
        },
        'country',
])->all();


findOne()和findAll():
// 查询key值为10的客户
$customer = Customer::findOne(10);
$customer = Customer::find()->where(['id' => 10])->one();
// 查询年龄为30,状态值为1的客户
$customer = Customer::findOne(['age' => 30, 'status' => 1]);
$customer = Customer::find()->where(['age' => 30, 'status' => 1])->one();
// 查询key值为10的所有客户
$customers = Customer::findAll(10);
$customers = Customer::find()->where(['id' => 10])->all();
// 查询key值为1011,12的客户
$customers = Customer::findAll([10, 11, 12]);
$customers = Customer::find()->where(['id' => [10, 11, 12]])->all();
// 查询年龄为30,状态值为1的所有客户
$customers = Customer::findAll(['age' => 30, 'status' => 1]);
$customers = Customer::find()->where(['age' => 30, 'status' => 1])->all();


where()条件:
$customers = Customer::find()->where($cond)->all(); 

$cond = ['type' => 1, 'status' => 2]
$cond = ['id' => [1, 2, 3], 'status' => 2] 
$cond = ['status' => null]

//and
$cond = ['and', 'id=1', 'id=2']
$cond = ['and', 'type=1', ['or', 'id=1', 'id=2']]

//or
$cond = ['or', ['type' => [7, 8, 9]], ['id' => [1, 2, 3]]

//not
$cond = ['not', ['attribute' => null]]

//between
$cond = ['between', 'id', 1, 10]

//in
$cond = ['in', 'id', [1, 2, 3]]
$cond = ['in', ['id', 'name'], [['id' => 1, 'name' => 'foo'], ['id' => 2, 'name' => 'bar']]]
$cond = ['in', 'user_id', (new Query())->select('id')->from('users')->where(['active' => 1])]

//like
$cond = ['like', 'name', 'tester']
$cond = ['like', 'name', ['test', 'sample']]
$cond = ['like', 'name', '%tester', false]

//exists
$cond = ['exists', (new Query())->select('id')->from('users')->where(['active' => 1])]

//运算符
$cond = ['>=', 'id', 10]
$cond = ['!=', 'id', 10]




User::find()->select('user_id,user_name')->where(['uid'=>'1'])->asArray()->one() 
User::find()->select('username')->where(['uid'=>'1'])->scalar(); 

User::find()->select('*')->where(['>=', 'admin_id', 10])->offset(0)->limit(10)->all()

$subQuery = (new Query())->select('COUNT(*)')->from('user');    
$query = (new Query())->select(['id', 'count' => $subQuery])->from('post');

User::find()->select('user_id')->distinct();


$model = TopNews::find()
    ->where(['and', ['<=', 'start_time', $time], ['>=', 'end_time', $time], ['=', 'status', 1]])
    ->asArray()->all();

$model = (new \yii\db\Query())
            ->from('{{%article}}')
            ->select('art_id, title, updated_at, image')
            ->where(['cat_id' => $cat_id, 'status' => 1])
            ->orderBy('sort_order Desc')
            ->offset($offset)
            ->limit($size)
            ->all();

//join 
$models = (new \yii\db\Query())
            ->select('u.id, u.username, u.realname, u.email, u.status, u.group_id, g.group_name')
            ->from('{{%user}} as u')
            ->join('LEFT JOIN', '{{%user_group}} as g', 'u.group_id = g.group_id')
            ->where(['u.parent_id' => $userId])
            ->offset($offset)
            ->limit($size)
            ->all();

// groupBy
$models = Contract::find()
            ->select("confirm_time, sum(money) as total_money")
            ->where(['status' => 1])
            ->groupBy(['FROM_UNIXTIME(confirm_time, \'%Y-%m\')'])
            ->having(['FROM_UNIXTIME(confirm_time, \'%Y-%m\')' => $month])
            ->asArray()->all();

















//查看执行sql
echo UserModel::find()->where(['status'=>1])->createCommand()->getRawSql();
查看是否报错
var_dump(UserModel::getErrors());






delete('{{student}}', ['in','id',[1,2,3]])



update('{{student}}', ['grade'=>'99'], ['xingming'=>$xm,'xingbie'=>$xb])
update('{{student}}', ['grade'=>'99'], 'xingming=:xm and xingbie=:xb', [':xm'=>$xm,':xb'=>$xb])


(new \yii\db\Query())->from($this->tableNetworkingStoreMonth)
->where(['=', 'date', $month])->andWhere(['=', 'store', $store])->count('id');

(new \yii\db\Query())->select(['sum(`num`) as `nums'])->from($table)
->where('`date`=:date')
->addParams([':date' => $date])
->andWhere(['in', 'store', $storeArray])



$StudentModel->find()->select('date'.$str)
->where(['and', ['>=', 'date', $start_date], ['<=', 'date', $end_date]])
->groupBy('date')->orderBy('date asc')->asArray()->all();


Student::find()->select('orgCode, lng, lat')
->where(['treeLevel' => $treeLevel])->asArray()->all();


$result = $TrafficModel->find() ->select('date'.$str)
->where(['and', ['>=', 'date', $start_date], ['<=', 'date', $end_date]])
->groupBy('date')->orderBy('date asc')->asArray()->all();












































阅读更多
个人分类: yii2
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

yii2增删改查

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭