Yii2框架数据库增删改查

Posted 天行子

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Yii2框架数据库增删改查相关的知识,希望对你有一定的参考价值。

查询操作:

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()->where([\'name\' => \'username\'])->one();   此方法返回 [\'name\' => \'username\'] 的一条数据;
User::find()->where([\'name\' => \'username\'])->all();   此方法返回 [\'name\' => \'username\'] 的所有数据;
User::find()->andWhere([\'sex\' => \'男\', \'age\' => \'24\'])->count(\'id\');   统计符合条件的总条数;
$student = Student::find()->where([\'status\'=>ConfigHelper::STATUS_ABLE])->count();
$student = Student::findOne(7688);
$student =(new Query())->from(\'student\')->select([\'id\',\'username\'])->where([\'id\'=>7688])->one();

$connection = Yii::$app->db;
$sql = "select * from student limit 1";
$student = $connection->createCommand($sql)->queryAll();

$sql = \'SELECT * FROM student limit 10\';
 $student = Student::findBySql($sql)->asArray()->all();

each查询

 $query = (new Query())->from(\'student\')->where([\'classes_id\'=>6])->batch(10);

echo \'<pre>\';
foreach ($query as $students){
    var_dump($students);
}

batch查询

$query = (new Query())->from(\'student\')->where([\'classes_id\'=>6])->each(10);
echo \'<pre>\';
foreach ($query as $students){
    var_dump($students);
}

新增操作:

$model = newUser();
$model->username = \'username\';
$model->age      = \'20\';
$model->insert();

$connection = Yii::$app->db;
$r = $connection->createCommand()
->insert(\'classes\',[\'name\'=>\'class\',\'school_id\'=>67843,\'comment\'=>\'test\',\'is_pay\'=>0,\'account_type_id\'=>2])
->execute();

$class = new Classes();
$class->name = \'class2\';
$class->school_id = 67843;
$r = $class->save();

批量插入

$connection = Yii::$app->db;
$r = $connection->createCommand()
->batchInsert(\'classes\',[\'name\',\'school_id\'],[[\'class3\',\'67843\'],[\'class4\',\'67843\']])
->execute();

修改操作:

$User = User::findOne($id);
$User->name = \'zhangsan\';
$User->save(); // 等同于 $User->update();

删除操作:

User::deleteAll(\'name = username\');    删除 name = username 的数据;
User::findOne($id)->delete(); 删除主键为 $id变量 值的数据库;
User::deleteAll(\'age > :age AND sex = :sex\', [\':age\' => \'20\', \':sex\' => \'1\']);  删除符合条件的数据;

以上是关于Yii2框架数据库增删改查的主要内容,如果未能解决你的问题,请参考以下文章

Yii2框架数据库增删改查

Yii2.0实现框架增删改查

yii2 框架的 AR 和 DAO 增删改查

YII2.0 数据库增删改查

yii2-basic后台管理功能开发之二:创建CRUD增删改查

Yii2.0数据库操作增删改查详解