学习使用yii2框架查询数据库model的超详解说并举例
学习使用yii2框架查询数据库model的超详解说并举例
- all() 查询全部
- findOne()返回指定数据
- where()和one()组合
- where()和all()组合
- orderBy()和all()组合
- findBySql()
- andWhere 组合查询
- asArray()以数组形式显示
- count()返回总条数
- count()和groupBy()组合返回查询总条数
- andFilterWhere() 控制where属性
- average()指定列的平均值
- min()指定列的最小值
- max()指定列的最大值
- scalar()第一行第一列的查询结果
- column()第一列的值
- exists()指定列的平均值
- offset()和limit()组合实现分页查询
all() 查询全部
$order_all = SaleOrder::find()->all();
此方法返回所有数据
findOne()返回指定数据
$order_all = SaleOrder::findOne(5);
此方法返回id=5的数据
where()和one()组合
$order_all = SaleOrder::find()->where(['product_brand' => '弯刀'])->one();
此方法返回’product_brand’ => ‘弯刀’] 的一条数据
where()和all()组合
$order_all = SaleOrder::find()->where(['product_brand' => '弯刀'])->all();
此方法返回’product_brand’ => ‘弯刀’] 的所有数据
orderBy()和all()组合
$order_all = SaleOrder::find()->orderBy('id desc')->all();
此方法是排序查询,默认为正序,可传参修改排序规则
findBySql()
$order_all = SaleOrder::findBySql('select * from mdz_sale_order')->one();
$order_all = SaleOrder::findBySql('select * from mdz_sale_order')->all();
传入sql语句得到数据
andWhere 组合查询
$order_all = SaleOrder::find()->andWhere(['product_brand' => '熊猫60','company_id' => '2'])->all();
asArray()以数组形式显示
$order_all = SaleOrder::find()->andWhere(['product_brand' => '熊猫60','company_id' => '2'])->asArray()->all();
count()返回总条数
$order_all = SaleOrder::find()->andWhere(['product_brand' => '熊猫60','company_id' => '2'])->count('id');
count()和groupBy()组合返回查询总条数
$order_all = SaleOrder::find()->where(['company_id' => 2])->groupBy('product_brand')->asArray()->count();
andFilterWhere() 控制where属性
$order_all = SaleOrder::find()->andFilterWhere(['like','product_brand','弯刀'])->asArray()->all();
返回符合条件的所有数据
average()指定列的平均值
$order_all = SaleOrder::find()->where(['company_id' => 2])->average('company_id');
此方法返回指定列的平均值,保留4位小数
min()指定列的最小值
$order_all = SaleOrder::find()->where(['company_id' => 2])->min('store_id');
传入指定列的名称,并返回指定列的最小值
max()指定列的最大值
$order_all = SaleOrder::find()->where(['company_id' => 2])->max('store_id');
传入指定列的名称,并返回指定列的最大值
scalar()第一行第一列的查询结果
$order_all = SaleOrder::find()->where(['company_id' => 2])->scalar();
$order_all = SaleOrder::find()->scalar();
返回查询数据的第一行第一列的值
column()第一列的值
什么都不传,默认返回第一列的所有值
$order_all = SaleOrder::find()->where(['company_id' => 2])->column();
传入一个指定列,则会返回指定列的所有值
$order_all = SaleOrder::find()->select('product_brand')->where(['company_id' => 2])->column();
传入多个字段,则会返回第一个字段对应列的所有值
$order_all = SaleOrder::find()->select('product_brand,company_id')->where(['company_id' => 2])->column();
exists()指定列的平均值
$order_all = SaleOrder::find()->where(['company_id' => 2])->exists();
$order_all = SaleOrder::find()->where(['company_id' => 2000])->exists();
此方法返回一个值指示是否包含查询结果的数据行,存在则是1,否则为空
offset()和limit()组合实现分页查询
$pageSize = 10;
$page = 1;
$order_all = SaleOrder::find()->where(['company_id' => 2])->orderBy('id asc')->offset($page * $pageSize)->limit($pageSize)->asArray()->all();
传入当前页码和显示条数,以数组的方式返回
还没有评论,来说两句吧...