nest商城项目商品的管理(五)

257 阅读2分钟

因为从事的一直是前端相关的开发,想接触一下后端的知识,发现nestjs这个框架也可以写后台接口,于是从网上找到一个Java比较完善的商城项目,按照这个Java项目翻成了nestjs的项目,这个项目仅限于我自己的学习过程,把学习过程中的内容分享出来,希望大家可以一起讨论进步

Java项目地址,这个Java项目的教程感觉还是比较完善的,有兴趣的可以去看看。我只是用nestjs写了一下接口,后台管理系统和前端APP还是这个项目的代码,只是修改了一部分配置,所以,运行的时候还是要下载我里面的前端代码, uniapp项目的接口暂时没时间写,所以只能看后台了

这个项目里面商品的管理涉及到的表也比较多,觉得商品这里需要说明一下,typeorm里面有一对一,一对多的关系,我理解这个就是为了更好的处理返回的数据格式,我在role的模块里面没用使用关系处理,而是直接像这样处理查询,也可以满足需要

   const sql = await this.rmrRepository
      .createQueryBuilder('rmr')
      .leftJoinAndSelect(UmsMenu, 'mr', 'mr.id = rmr.menuId')
      .where('rmr.roleId = :roleId', { roleId: roleId })
      .addGroupBy('mr.id')
      .select(
        `mr.id as id,
         mr.name as name,
         mr.parentId as parentId,
         mr.createTime as createTime,
         mr.title as title,
         mr.level as level,
         mr.sort as sort,
         mr.icon as icon,
         mr.hidden as hidden
      `,
      )
      .printSql()
      .getRawMany();

而商品管理这里我试验了一下关系的处理,比如这个实体,product对应的就是商品的实体,而productLadderList就是要返回的数据

import { ApiProperty } from '@nestjs/swagger';
import {
  Column,
  Entity,
  JoinColumn,
  ManyToOne,
  PrimaryGeneratedColumn,
} from 'typeorm';
import { Product } from './product.entity';

@Entity('pms_product_ladder')
export class ProductLadder {
  @ApiProperty({ description: '自增 id' })
  @PrimaryGeneratedColumn({ type: 'bigint' })
  id: number;

  @ApiProperty({ description: '' })
  @Column({ type: 'bigint', name: 'product_id' })
  productId: number;

  @ApiProperty({ description: '满足的商品数量' })
  @Column({ type: 'int' })
  count: number;

  @ApiProperty({ description: '折扣' })
  @Column({ type: 'decimal' })
  discount: number;

  @ApiProperty({ description: '折后价格' })
  @Column({ type: 'decimal' })
  price: number;

  @ManyToOne((type) => Product, (product) => product.productLadderList)
  @JoinColumn({ name: 'product_id' })
  product: Product;
}

经过对关系的处理以后,查询的时候只需要获取实体就可以,而不必像上面那样重新取别名返回,当然如果直接取getOne,而不需要原始sql,也不用取别名

   const sql = await this.pmsRepository
      .createQueryBuilder('p')
      .leftJoinAndSelect('p.productCategory', 'productCategory')
      .leftJoinAndSelect('p.productLadderList', 'productLadderList')
      .leftJoinAndSelect('p.skuStockList', 'skuStockList')
      .leftJoinAndSelect(
        'p.productAttributeValueList',
        'productAttributeValueList',
      )
      .leftJoinAndSelect('p.memberPriceList', 'memberPriceList')
      .leftJoinAndSelect(
        'p.productFullReductionList',
        'productFullReductionList',
      )
      .leftJoinAndSelect(
        'p.prefrenceAreaProductRelationList',
        'prefrenceAreaProductRelationList',
      )
      .leftJoinAndSelect(
        'p.subjectProductRelationList',
        'subjectProductRelationList',
      )
      .where('p.id = :id', { id: productId })
      .printSql()
      .getOne();

所有代码在目录/src/modules/product