首页 > 解决方案 > “where 子句”中的未知列“{columnName}”

问题描述

当使用 typeorm 存储库函数findOne或 QueryBuilder 时,例如:

  constructor (
    @InjectRepository(EntityName)
    private entityNameRepository: Repository<EntityName>,
  ) {}

  ...

    const qb = this.entityNameRepository.createQueryBuilder('e');
    qb.where('e.originKey=:origin_key', {
      origin_key: originKey,
    });

    const entityName: EntityName = await qb.getOne();

    // or

    const entityName: EntityName = await this.entityNameRepository.findOne({
       originKey: originKey,
    });

我收到以下错误消息:

QueryFailedError: Unknown column 'originKey' in 'where clause'
    at new QueryFailedError (/Users/{project}/node_modules/typeorm/error/QueryFailedError.js:11:28)
    at Query.onResult (/Users/{project}/node_modules/typeorm/driver/mysql/MysqlQueryRunner.js:216:45)
    at Query.execute (/Users/{project}/node_modules/mysql2/lib/commands/command.js:30:14)
    at PoolConnection.handlePacket (/Users/{project}/node_modules/mysql2/lib/connection.js:425:32)
    at PacketParser.Connection.packetParser.p [as onPacket] (/Users/{project}/node_modules/mysql2/lib/connection.js:75:12)
    at PacketParser.executeStart (/Users/{project}/node_modules/mysql2/lib/packet_parser.js:75:16)
    at Socket.Connection.stream.on.data (/Users/{project}/node_modules/mysql2/lib/connection.js:82:25)
    at Socket.emit (events.js:182:13)
    at addChunk (_stream_readable.js:287:12)
    at readableAddChunk (_stream_readable.js:268:11)

我的实体看起来像:

import { BaseEntity, Column, Entity, PrimaryGeneratedColumn } from 'typeorm';
import { UuidGenerator } from '../adapter/uuid-generator';

@Entity()
export class EntityName extends BaseEntity {
  @PrimaryGeneratedColumn({ name: 'id' })
  id: number;

  @Column({ name: 'uuid', unique: true, nullable: false })
  uuid: string;

  @Column({ name: 'is_active', default: true })
  isActive: boolean;

  @Column({ name: 'origin_key', unique: true, nullable: true })
  originKey: string;
}

MySQL中的列称为origin_key

当我强制使用属性名称进行查询时,origin_key它也会失败,并显示一个不同的错误,告诉实体中没有给出该字段,由于命名,这是有道理的。

标签: mysqlnestjstypeorm

解决方案


编辑:与往常一样,问题出现在屏幕前面:问题是传递的参数:它不是一个标量值,而是一个像这样的对象:({ originKey: 111 }预期是一个字符串),所以我被误导了方向,与定义无关。错误消息指向传递的对象,而不是我的实体的列/属性。


推荐阅读