【Yii2】数据库查询方法总结

目录

1.查找单个记录:

2.查找多个记录:

3.条件查询:

4.关联查询: 假设User模型有一个名为orders的多对一关联关系。

5.排序和分组:

6.数据操作:

7.事务处理:

8.命令查询:

9.count查询

 10.使用ActiveQuery类提供的各种方法来构建复杂的查询


Yii2是一个功能丰富的PHP框架,提供了大量的数据库查询方法和功能,以便开发人员能够方便地对数据库进行操作。以下是Yii2中一些常用的数据库查询方法的总结:

这些示例假设你已经有了一个名为User的模型,它代表了数据库中的user表,并且该表有id、username、email和status字段。

1.查找单个记录:


// 查找ID为1的用户
$user = User::findOne(1);

2.查找多个记录:


// 查找所有状态为'active'的用户
$users = User::findAll(['status' => 'active']);

3.条件查询:


// 查找状态为'active'的用户
$users = User::find()->where(['status' => 'active'])->all();

4.关联查询: 假设User模型有一个名为orders的多对一关联关系。


// 获取用户及其订单信息
$users = User::find()->with('orders')->all();

5.排序和分组:


// 按照用户名升序排序
$users = User::find()->orderBy('username ASC')->all();

// 按照状态分组
$users = User::find()->groupBy('status')->all();

6.数据操作:


// 插入新用户
$newUser = new User();
$newUser->username = 'newuser';
$newUser->email = '[email protected]';
$newUser->status = 'active';
$newUser->save(); // 或者 $newUser->insert();

// 更新用户
$user = User::findOne(1);
$user->username = 'updateduser';
$user->save(); // 或者 $user->update();

// 删除用户
$user = User::findOne(1);
$user->delete();

7.事务处理:


// 开始事务
$transaction = Yii::$app->db->beginTransaction();

try {
    // 执行一系列数据库操作...
    $user->save();
    // 其他操作...

    // 提交事务
    $transaction->commit();
} catch (\Exception $e) {
    // 回滚事务
    $transaction->rollBack();
    // 处理异常...
}

8.命令查询:


// 执行原生SQL命令
$command = Yii::$app->db->createCommand('SELECT * FROM user WHERE status = :status', [':status' => 'active']);
$users = $command->queryAll();

9.count查询


// 假设有一个名为Post的模型类,代表博客文章
// Post是ActiveRecord的一个实例
$query = Post::find(); // 创建一个查询实例

// 统计所有文章的数量
$count = $query->count(); // 返回文章的总数

// 你也可以将统计结果作为数组的一部分返回
$ posts = Post::find()->count();

// 如果要统计带有特定条件的文章数量
$count = Post::find()->where(['status' => 'published'])->count(); // 只统计发布状态的文章

// 你也可以链式调用其他查询方法
$count = Post::find()->where(['status' => 'published'])->limit(10)->count(); // 统计最近10篇发布状态的文章的数量

 10.使用ActiveQuery类提供的各种方法来构建复杂的查询



// 使用比较操作符
$query = Post::find()->where(['status' => 'published'])->andWhere(['created_at' => '<', new \DateTime()]); // 查找发布状态的文章,且创建时间早于当前时间的文章

// 使用范围查询
$query = Post::find()->where(['status' => 'published'])->andWhere(['created_at' => BETWEEN, [new \DateTime('2023-01-01'), new \DateTime('2023-12-31')]]); // 查找发布状态的文章,且创建时间在2023年1月1日至2023年12月31日之间的文章

// 你也可以直接使用范围查询的简写形式
$query = Post::find()->where(['status' => 'published'])->andWhere(['created_at' => 'BETWEEN', [new \DateTime('2023-01-01'), new \DateTime('2023-12-31')]]); // 同上,使用BETWEEN进行范围查询

// 你可以使用链式调用来组合多个条件
$query = Post::find()->where(['status' => 'published'])->andWhere(['created_at' => '<', new \DateTime()])->orWhere(['created_at' => BETWEEN, [new \DateTime('2023-01-01'), new \DateTime('2023-12-31')]]); // 查找发布状态的文章,且创建时间早于当前时间,或者创建时间在2023年1月1日至2023年12月31日之间的文章

// 你还可以使用`notBetween`来查询不在指定范围内的数据
$query = Post::find()->where(['status' => 'published'])->andWhere(['created_at' => 'NOT BETWEEN', [new \DateTime('2023-01-01'), new \DateTime('2023-12-31')]]); // 查找发布状态的文章,且创建时间不在2023年1月1日至2023年12月31日之间的文章

Post::find()->where(['in', 'uid', $arr])->andWhere(['not in', 'order_status', [-1, 2]])->groupBy('uid')->count();

Post::find()->where(['type' => '1'])->andWhere(['between', 'updated_at', $curMonth, $nexMonth])->sum('price');

Post::find()->select('id, nickname, mobile, money, status, created_at')
                ->where(['uid' => $this->uid])
                ->andWhere(['>', 'created_at', $data['startTime']-(3600*24*2)])
                ->andWhere(['<=', 'created_at', $data['startTime']-(3600*24)])
                ->orderBy('created_at desc')
                ->asArray()->one();

请注意,这些示例中的User模型应当是一个已经定义好的模型类,它继承了yii\db\ActiveRecord。在实际应用中,你可能需要根据具体的表结构和业务逻辑来调整这些示例代码。此外,Yii2的数据库操作通常会结合其 ActiveForm 和 GridView 等组件来提高开发效率。

你可能感兴趣的:(php,yii2,数据库,php,yii)