【问题标题】:How to create a query using typeorm query builder to filder data from the database?如何使用 typeorm 查询生成器创建查询以过滤数据库中的数据?
【发布时间】:2020-07-01 13:53:03
【问题描述】:

我是 typeorm 的新手,我正在使用 nodejs/nestjs,我正在尝试创建一个查询,其中来自数据库的数据是课程可以由讲师过滤,即名字和姓氏,过滤 course_name 和按主题过滤课程。我尝试使用 'where' 和 'orWhere' 但似乎无法结束,任何人都可以提供更好的实施建议吗?谢谢你。非常感谢。

下面的查询正在运行,我在“where”条件下遇到问题

代码

async findAll(options: IPaginationOptions, query): Promise<Pagination<CourseEntity>> {
    console.log('query :', query);
    const courses = await getRepository(CourseEntity)
      .createQueryBuilder('course')
      .leftJoinAndSelect('course.user', 'user')
      .leftJoinAndSelect('course.subject', 'subject')
      // eslint-disable-next-line @typescript-eslint/camelcase
      .where('course.course_name = :course_name', { course_name: query.course_name });

    return paginate<CourseEntity>(courses, options);
  }

这里是查询参数

query : { limit: '10', firstname: 'mark', lastname: 'gunn' , course_name: 'Comscie'}

来自数据库的样本数据

 {
            "id": 4,
            "course_name": "BS-IT",
            "description": "BS-IT DBMS",
            "created": "2020-03-19T16:40:46.000Z",
            "updated": "2020-03-19T16:40:46.000Z",
            "user": {
                "id": 20,
                "firstname": "Mark",
                "lastname": "Gunn",
                "role": "Instructor",
                "email": "mark@gmail.com",
                "isActive": false,
                "created": "2020-03-19T16:06:21.000Z",
                "updated": "2020-03-19T16:06:34.000Z"
            },
            "subject": {
                "id": 2,
                "subject_name": "IT 100",
                "description": "Fundamandetals",
                "created": "2020-03-18T03:58:34.000Z",
                "updated": "2020-03-18T03:58:34.000Z"
            }
        }

【问题讨论】:

    标签: javascript node.js typescript nestjs typeorm


    【解决方案1】:

    对于我使用 Typeorm 的项目,我更喜欢使用 Find Option Object (https://typeorm.io/#/find-options),因为从对象生成请求更容易,但你不能进行一些高级连接(但在你的情况下它完全没问题)

    它们并不是更好的实现,只是多种解决方案。

    【讨论】:

      【解决方案2】:

      看起来不错。只需使用 andWhere 添加其他条件

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-07-27
        • 2016-06-06
        • 1970-01-01
        • 1970-01-01
        • 2020-03-28
        • 1970-01-01
        • 2013-12-13
        • 1970-01-01
        相关资源
        最近更新 更多