App后台管理系统后端常用Sql操作


prtyaa
prtyaa 2024-02-04 20:56:50 52327 赞同 0 反对 0
分类: 资源 标签: 运维
本文列举几个app后端管理系统前后端交互时候常见的几种对于数据库的操作行为,以及使用node实现的代码,希望对您有所帮助。

1. 基本查询

基本查询通常用于检索满足特定条件的数据集。这包括按特定字段的值查找、获取所有数据等。

// 获取所有数据
const getAllItems = async (req, res) => {
  try {
    const items = await Item.findAll();
    res.json(items);
  } catch (error) {
    res.status(500).send({ message: error.message });
  }
};

// 按条件查询
const getItemsByCondition = async (req, res) => {
  try {
    const items = await Item.findAll({
      where: {
        // 条件,例如 status: 'active'
      }
    });
    res.json(items);
  } catch (error) {
    res.status(500).send({ message: error.message });
  }
};

2. 关联查询

关联查询用于检索与其他表相关联的数据。在 Sequelize 中,这通常涉及 include 选项。

const getItemsWithDetails = async (req, res) => {
  try {
    const items = await Item.findAll({
      include: [{ model: DetailModel }] // 关联其他模型
    });
    res.json(items);
  } catch (error) {
    res.status(500).send({ message: error.message });
  }
};

3. 分页

分页是后台管理系统中一个重要的特性,它允许服务器一次只发送部分数据,减轻服务器负担,提高用户体验。

const getItemsPaginated = async (req, res) => {
  const page = parseInt(req.query.page) || 1;
  const pageSize = parseInt(req.query.pageSize) || 10;

  try {
    const { count, rows } = await Item.findAndCountAll({
      offset: (page - 1) * pageSize,
      limit: pageSize
    });
    res.json({
      total: count,
      data: rows,
      page: page,
      pageSize: pageSize
    });
  } catch (error) {
    res.status(500).send({ message: error.message });
  }
};

4. 更新数据

更新操作允许修改现有数据库记录。这可以是单个字段的更新,也可以是多个字段的更新。

const updateItem = async (req, res) => {
  try {
    const [updated] = await Item.update(req.body, {
      where: { id: req.params.id }
    });
    if (updated) {
      const updatedItem = await Item.findByPk(req.params.id);
      res.json(updatedItem);
    } else {
      res.status(404).send({ message: 'Item not found' });
    }
  } catch (error) {
    res.status(500).send({ message: error.message });
  }
};

5. 删除数据

删除操作用于从数据库中移除数据。这可以是单个记录的删除或符合特定条件的多条记录的批量删除。

const deleteItem = async (req, res) => {
  try {
    const deleted = await Item.destroy({
      where: { id: req.params.id }
    });
    if (deleted) {
      res.json({ message: 'Item deleted successfully' });
    } else {
      res.status(404).send({ message: 'Item not found' });
    }
  } catch (error) {
    res.status(500).send({ message: error.message });
  }
};

这些是后台管理系统中最常见的数据库操作,它们涵盖了绝大多数的日常需求。根据具体的业务逻辑,可能还需要进行更多定制化的操作。

6. 批量插入

当需要一次性插入多条数据时,批量插入是非常有用的。

const bulkInsertItems = async (req, res) => {
  try {
    const items = req.body.items; // 假设是一个对象数组
    await Item.bulkCreate(items);
    res.json({ message: 'Items were added successfully' });
  } catch (error) {
    res.status(500).send({ message: error.message });
  }
};

7. 复杂查询

涉及多个条件、子查询、聚合函数(如 COUNT、MAX)的复杂查询。

const getComplexData = async (req, res) => {
  try {
    const data = await Item.findAll({
      where: {
        // 复杂条件
      },
      include: [{
        model: AnotherModel,
        required: true
      }],
      group: ['Item.column'],
      having: Sequelize.where(Sequelize.fn('COUNT', Sequelize.col('Item.column')), '>', 1)
    });
    res.json(data);
  } catch (error) {
    res.status(500).send({ message: error.message });
  }
};

8. 事务处理

对于需要保证数据完整性的复杂操作,使用事务是必须的。

const performComplexOperation = async (req, res) => {
  const transaction = await sequelize.transaction();
  try {
    // 多个数据库操作
    await Model1.create({ ... }, { transaction });
    await Model2.update({ ... }, { where: { ... } }, { transaction });

    await transaction.commit();
    res.json({ message: 'Operation successful' });
  } catch (error) {
    await transaction.rollback();
    res.status(500).send({ message: error.message });
  }
};

9. 数据统计和聚合

对数据进行统计分析,例如计算总数、平均值等。

const getStatistics = async (req, res) => {
  try {
    const stats = await Item.findAll({
      attributes: [
        [Sequelize.fn('COUNT', Sequelize.col('id')), 'totalItems'],
        [Sequelize.fn('AVG', Sequelize.col('price')), 'averagePrice']
      ]
    });
    res.json(stats[0]);
  } catch (error) {
    res.status(500).send({ message: error.message });
  }
};

10. 软删除

标记数据为删除状态而非从数据库中完全移除。

const softDeleteItem = async (req, res) => {
  try {
    await Item.update({ deleted: true }, { where: { id: req.params.id } });
    res.json({ message: 'Item deleted successfully' });
  } catch (error) {
    res.status(500).send({ message: error.message });
  }
};

以上操作涵盖了后台管理系统中常用的数据库操作。根据实际业务需求,可能还会有更多特定的操作和策略。在设计数据库交互时,重要的是确保操作的安全性、效率和符合业务逻辑。

如果您发现该资源为电子书等存在侵权的资源或对该资源描述不正确等,可点击“私信”按钮向作者进行反馈;如作者无回复可进行平台仲裁,我们会在第一时间进行处理!

评价 0 条
prtyaaL2
粉丝 1 资源 1949 + 关注 私信
最近热门资源
银河麒麟桌面操作系统备份用户数据  126
统信桌面专业版【全盘安装UOS系统】介绍  121
银河麒麟桌面操作系统安装佳能打印机驱动方法  114
银河麒麟桌面操作系统 V10-SP1用户密码修改  105
最近下载排行榜
银河麒麟桌面操作系统备份用户数据 0
统信桌面专业版【全盘安装UOS系统】介绍 0
银河麒麟桌面操作系统安装佳能打印机驱动方法 0
银河麒麟桌面操作系统 V10-SP1用户密码修改 0
作者收入月榜
1

prtyaa 收益393.62元

2

zlj141319 收益218元

3

1843880570 收益214.2元

4

IT-feng 收益209.03元

5

风晓 收益208.24元

6

777 收益172.71元

7

Fhawking 收益106.6元

8

信创来了 收益105.84元

9

克里斯蒂亚诺诺 收益91.08元

10

技术-小陈 收益79.5元

请使用微信扫码

加入交流群

请使用微信扫一扫!