Yii2 增删改查(CRUD)
一、基本查询
User::find()->all(); //返回所有数据;
User::findOne($id); //返回 主键 id=1 的一条数据(举个例子);
User::find()->where(['name' => '小伙儿'])->one(); //返回 ['name' => '小伙儿'] 的一条数据;
User::find()->where(['name' => '小伙儿'])->all(); //返回 ['name' => '小伙儿'] 的所有数据;
User::find()->orderBy('id DESC')->all(); //是排序查询;
User::findBySql('SELECT * FROM user')->all(); //是用 sql 语句查询 user 表里面的所有数据;
User::findBySql('SELECT * FROM user')->one(); //是用 sql 语句查询 user 表里面的一条数据;
User::find()->andWhere(['sex' => '男', 'age' => '24'])->count('id'); //统计符合条件的总条数;
User::find()->andFilterWhere(['like', 'name', '小伙儿']); //是用 like 查询 name 等于 小伙儿的 数据
User::find()->one(); //返回一条数据;
User::find()->all(); //返回所有数据;
User::find()->count(); //返回记录的数量;
User::find()->average(); //返回指定列的平均值;
User::find()->min(); //返回指定列的最小值 ;
User::find()->max(); //返回指定列的最大值 ;
User::find()->scalar(); //返回值的第一行第一列的查询结果;
User::find()->column(); //返回查询结果中的第一列的值;
User::find()->exists(); //返回一个值指示是否包含查询结果的数据行;
User::find()->batch(10); //每次取 10 条数据
User::find()->each(10); //每次取 10 条数据, 迭代查询
原文链接:http://www.yiichina.com/tutorial/95
二、and 和 or 复合句
->andWhere['customer_id'=>$customerId]
->andWhere(['or'
['customer_name' => $customername],
['LIKE', 'phone' , $phone],
])
// WHERE customer_id=1 AND (customer_name='张三' OR phone LIKE 13123456789)
->andWhere['customer_id'=>$customerId]
->orWhere(['and'
['customer_name' => $customername],
['LIKE', 'phone' , $phone],
])
// WHERE customer_id=1 OR (customer_name='张三' AND phone LIKE 13123456789)
//2、如果需要些 and和or 的复合句,则:
->andWhere['customer_id'=>$customerId]
->andWhere(['or'
['status' => $status],
['and',
['customer_name' => $customername],
['LIKE', 'phone' , $phone],
],
])
// WHERE customer_id=1 AND ('status'=>1 OR (customer_name='张三' AND phone LIKE 13123456789))
//3、如果需要一些特殊的形式,则使用 new \yii\db\Expression();
->andWhere['customer_id'=>$customerId]
->andWhere(['or'
['status' => $status],
['and',
['customer_name' => $customername],
['IS NOT', phone' , new \yii\db\Expression('NULL')],
],
])
// WHERE customer_id=1 AND ('status'=>1 OR (customer_name='张三' AND phone IS NOT NULL))
三、modelName::updateAll($attributes, $condition = '', $params = [])
第一个参数是要更新的值,第二个是条件,如果第二个条件中用了占位符,就必须 要有第三个条件。 平时我们查询 的时候用 andWhere()
可以连接很多参数,那么 updateAll()
的时候,如果有多个参数怎么办?
User::updateAll(['status' => 1],['status' => 0,'flag' => 1]);
果参数都是固定值,这样的写法当然 OK,如果有范围值就只能这样写了,比如 flag != 1
怎么办?
User::updateAll(['status' => 1],['and', ['status' => 0],['<>', 'flag', 1]]);
原文链接:https://www.yiichina.com/tutorial/1842
`