使用 typeorm 在 postgres 中搜索数组中的项目

Win*_*ech 5 postgresql node.js express typescript typeorm

数据库:postgres

\n

ORM:类型

\n

框架:express.js

\n

我有一个表,其中一个名为 name 的字段projects是一个字符串数组。类型"varchar"在迁移中设置为 ,装饰器设置为"simple-array"

\n

在我的获取路线中,如果我收到查询,?project=name_of_the_project它应该尝试在简单数组中查找项目。

\n

对于搜索我的获取路线是这样的:

\n
studentsRouter.get("/", async (request, response) => {\n    const { project } = request.query;\n    const studentRepository = getCustomRepository(StudentRepository);\n    const students = project\n        ? await studentRepository\n                .createQueryBuilder("students")\n                .where(":project = ANY (students.projects)", { project: project })\n                .getMany()\n        : await studentRepository.find();\n    // const students = await studentRepository.find();\n    return response.json(students);\n}); \n
Run Code Online (Sandbox Code Playgroud)\n

问题是 I\xc2\xb4m 收到错误,指出右侧应该是一个数组。

\n
(node:38971) UnhandledPromiseRejectionWarning: QueryFailedError: op ANY/ALL (array) requires array on right side\n    at new QueryFailedError (/Users/Wblech/Desktop/42_vaga/src/error/QueryFailedError.ts:9:9)\n    at Query.callback (/Users/Wblech/Desktop/42_vaga/src/driver/postgres/PostgresQueryRunner.ts:178:30)\n    at Query.handleError (/Users/Wblech/Desktop/42_vaga/node_modules/pg/lib/query.js:146:19)\n    at Connection.connectedErrorMessageHandler (/Users/Wblech/Desktop/42_vaga/node_modules/pg/lib/client.js:233:17)\n    at Connection.emit (events.js:200:13)\n    at /Users/Wblech/Desktop/42_vaga/node_modules/pg/lib/connection.js:109:10\n    at Parser.parse (/Users/Wblech/Desktop/42_vaga/node_modules/pg-protocol/src/parser.ts:102:9)\n    at Socket.<anonymous> (/Users/Wblech/Desktop/42_vaga/node_modules/pg-protocol/src/index.ts:7:48)\n    at Socket.emit (events.js:200:13)\n    at addChunk (_stream_readable.js:294:12)\n(node:38971) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)\n(node:38971) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.\n
Run Code Online (Sandbox Code Playgroud)\n

它必须是该字段中的字符串数组,我可以\xc2\xb4t 使用外键。

\n

请在下面找到与此问题相关的我的迁移和模型:

\n

移民

\n
import { MigrationInterface, QueryRunner, Table } from "typeorm";\n\nexport class CreateStudents1594744103410 implements MigrationInterface {\n    public async up(queryRunner: QueryRunner): Promise<void> {\n        await queryRunner.createTable(\n            new Table({\n                name: "students",\n                columns: [\n                    {\n                        name: "id",\n                        type: "uuid",\n                        isPrimary: true,\n                        generationStrategy: "uuid",\n                        default: "uuid_generate_v4()",\n                    },\n                    {\n                        name: "name",\n                        type: "varchar",\n                    },\n                    {\n                        name: "intra_id",\n                        type: "varchar",\n                        isUnique: true,\n                    },\n                    {\n                        name: "projects",\n                        type: "varchar",\n                        isNullable: true,\n                    },\n                ],\n            })\n        );\n    }\n\n    public async down(queryRunner: QueryRunner): Promise<void> {\n        await queryRunner.dropTable("students");\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n

模型

\n
import { Entity, Column, PrimaryGeneratedColumn } from "typeorm";\n\n@Entity("students")\nclass Student {\n    @PrimaryGeneratedColumn("uuid")\n    id: string;\n\n    @Column()\n    name: string;\n\n    @Column()\n    intra_id: string;\n\n    @Column("simple-array")\n    projects: string[];\n}\n\nexport default Student;\n
Run Code Online (Sandbox Code Playgroud)\n

编辑-01

\n

在文档中我发现存储simple-array用逗号分隔的字符串。我认为这意味着它是一个字符串,单词之间用逗号分隔。在这种情况下,有没有办法找到项目字段中的字符串位于哪一行?

\n

链接 - https://gitee.com/mirrors/TypeORM/blob/master/docs/entities.md#column-types-for-postgres

\n

编辑02

\n

现场项目存储学生正在做的项目,因此数据库返回以下 json:

\n
  {\n    "id": "e586d1d8-ec03-4d29-a823-375068de23aa",\n    "name": "First Lastname",\n    "intra_id": "flastname",\n    "projects": [\n      "42cursus_libft",\n      "42cursus_get-next-line",\n      "42cursus_ft-printf"\n    ]\n  },\n
Run Code Online (Sandbox Code Playgroud)\n

Mik*_*nek 4

根据问题的评论和更新,@WincentyBertoniLech 确定 ORM 将数组存储projects为列中逗号分隔的文本值students.projects

我们可以将string_to_array()其转化为正确的where标准:

.where(":project = ANY ( string_to_array(students.projects, ','))", { project: project })
Run Code Online (Sandbox Code Playgroud)