小编给大家分享一下YII2数据库如何查询,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!

数据库配置。
/config/db.php 进行数据库配置
实践过程中有个test库-》test表-》两条记录如下
mysql> select * from test; +----+--------+ | id | name | +----+--------+ | 1 | zhuai | | 2 | heng | +----+--------+ 18 rows in set (0.00 sec)
sql 查询方式
yii2 提供了原始的数据库查询方式findBySql;同时, 通过占位符的方式,自动进行了基本的sql注入防御 。上码
// 最基本的查询方式
$sql = "select * from test where 1";
$res = Test::findBySql($sql)->all();
var_dump(count($res)); // res->2
// findbysql 防止sql注入方式
$id = '1 or 1=1';
$sql = "select * from test where id = " . $id;
$res = Test::findBySql($sql)->all();
var_dump(count($res)); // res-> 2
$sql = "select * from test where id = :id";
// 定位符会自动防止sql 注入
$res = Test::findBySql($sql,array(":id"=>$id))->all();
var_dump(count($res)); // res->1activeRecord查询方式
每个框架除了原有的sql方式,都会提供相应的封装的查询方式,yii2亦然。
创建model
yii的model基本方式如下,代码如下不赘述。
[0, 100]], ]; } }
使用的时候需要引入model
use app\models\Test;
增加操作
// add 操作
$test = new Test();
$test->name = 'test';
// 合法性校验
$test->validate();
if($test->hasErrors()){
echo "数据不合法";
die;
}
$test->save();查询操作
查询操作先上官方文档
activeRecord doc
where doc
需要强调的是:yii查询提供了特别多丰富的库,例如代码中的批量查询处理等等,细节可以看文档。
// select
// id = 1
$res = Test::find()->where(['id' => 1])->all();
var_dump(count($res)); //1
// id > 0
$res = Test::find()->where(['>','id',0])->all();
var_dump(count($res)); //2
// id > =1 id <=2
$res = Test::find()->where(['between','id',1,2])->all();
var_dump(count($res)); //2
// name字段like
$res = Test::find()->where(['like', 'name', 'cuihuan'])->all();
var_dump(count($res)); //2
// 查询的使用 obj->array
$res = Test::find()->where(['between','id',1,2])->asArray()->all();
var_dump($res[0]['id']); //2
// 批量查询,对于大内存操作的批量查询
foreach (Test::find()->batch(1) as $test) {
var_dump(count($test));
}删除操作
// delete
// 选出来删除
$res = Test::find()->where(['id'=>1])->all();
$res[0]->delete();
// 直接删除
var_dump(Test::deleteAll('id>:id', array(':id' => 2)));修改操作
除了代码中方式,yii2直接提供update操作。
// 活动记录修改 $res = Test::find()->where(['id'=>4])->one(); $res->name = "update"; $res->save();
关联查询操作
关联查询示例中两个表:
一个学生表(student):id ,name;
一个分数表(score):id,stu_id,score
// 相应学生的所有score
$stu = Student::find()->where(['name'=>'xiaozhuai'])->one();
var_dump($stu->id);
// 基本获取
$scores_1 = $stu->hasMany('app\model\Score',['stu_id'=>$stu->id])->asArray()->all();
$scores_2 = $stu->hasMany(Score::className(),['stu_id'=>'id'])->asArray()->all();
var_dump($scores_1);
var_dump($scores_2);两种关联查询方式;但是,在controller进行相关操作,代码显的过于混乱,在model中封装调用
首先在student model中封装相关关联调用函数
hasMany(Score::className(), ['stu_id' => 'id'])->asArray()->all(); return $scores; } }
之后直接调用,两种调用方式
// 函数封装之后调用 $scores = $stu->getScores(); var_dump($scores); // 利用__get 的自动调用的方式 $scores = $stu->scores; var_dump($scores);
以上是“YII2数据库如何查询”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注创新互联行业资讯频道!