Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ER_BAD_FIELD_ERROR: Unknown column 'treeEntity.parentId' in 'where clause #2361

Open
newcomein opened this issue Jun 19, 2018 · 27 comments
Open

Comments

@newcomein
Copy link

newcomein commented Jun 19, 2018

Issue type:

[ x ] question
[ ] bug report
[ ] feature request
[ ] documentation issue

Database system/driver:

[ ] cordova
[ ] mongodb
[ ] mssql
[ x] mysql / mariadb
[ ] oracle
[ ] postgres
[ ] sqlite
[ ] sqljs
[ ] react-native

TypeORM version:

[x ] latest
[ ] @next
[ ] 0.x.x (or put your version here)

Steps to reproduce or a small repository showing the problem:

url: documentation http://typeorm.io/#/tree-entities/working-with-tree-entities

code:


async videoCategoryList(): Promise<any> {
    const manager = getManager();

    const a1 = new Category();
    a1.name = "a1";
    await manager.save(a1);

    return await manager.getTreeRepository(Category).findRoots();
  }


@Entity()
@Tree('closure-table')
export class Category {

  @PrimaryGeneratedColumn('uuid', { comment: '唯一id' })
  video_category_id: string;

  @Column({ comment: '菜单名' })
  name: string;

  @Column({ type: 'enum', enum: ['0', '1'], comment: '视频分类,未定义的分类' })
  type: string;

  @TreeChildren()
  children: Category[];

  @TreeParent()
  parent: Category;

}

Error:


{
    "message": "ER_BAD_FIELD_ERROR: Unknown column 'treeEntity.parentId' in 'where clause'",
    "code": "ER_BAD_FIELD_ERROR",
    "errno": 1054,
    "sqlMessage": "Unknown column 'treeEntity.parentId' in 'where clause'",
    "sqlState": "42S22",
    "index": 0,
    "sql": "SELECT `treeEntity`.`video_category_id` AS `treeEntity_video_category_id`, `treeEntity`.`name` AS `treeEntity_name`, `treeEntity`.`type` AS `treeEntity_type`, `treeEntity`.`parentVideoCategoryId` AS `treeEntity_parentVideoCategoryId` FROM `category` `treeEntity` WHERE `treeEntity`.`parentId` IS NULL",
    "name": "QueryFailedError",
    "query": "SELECT `treeEntity`.`video_category_id` AS `treeEntity_video_category_id`, `treeEntity`.`name` AS `treeEntity_name`, `treeEntity`.`type` AS `treeEntity_type`, `treeEntity`.`parentVideoCategoryId` AS `treeEntity_parentVideoCategoryId` FROM `category` `treeEntity` WHERE `treeEntity`.`parentId` IS NULL"
}

@pleerock
Copy link
Member

I already asked you to format code properly.

Please create a PR with a failing test which I can take a look (take a look how others do it).

@newcomein
Copy link
Author

image

Already code mode but editor identification failed @pleerock

@newcomein
Copy link
Author

It's my problem markdown unfamiliar

@pleerock
Copy link
Member

it gets few minutes to get familiar with markdown.

Please enable logging and show what schema queries typeorm executes for you

@newcomein
Copy link
Author


query: START TRANSACTION
query: INSERT INTO `category`(`video_category_id`, `name`, `type`, `parentVideoCategoryId`) VALUES (?, ?, DEFAULT, DEFAULT) -- PARAMETERS: ["bcb52a51-0583-4b9c-95d2-4504198d9f7b","a1"]
query: INSERT INTO `category_closure`(`video_category_id_ancestor`, `video_category_id_descendant`) VALUES (?, ?) -- PARAMETERS: ["bcb52a51-0583-4b9c-95d2-4504198d9f7b","bcb52a51-0583-4b9c-95d2-4504198d9f7b"]
query: COMMIT
query: SELECT `treeEntity`.`video_category_id` AS `treeEntity_video_category_id`, `treeEntity`.`name` AS `treeEntity_name`, `treeEntity`.`type` AS `treeEntity_type`, `treeEntity`.`parentVideoCategoryId` AS `treeEntity_parentVideoCategoryId` FROM `category` `treeEntity` WHERE `treeEntity`.`parentId` IS NULL
query failed: SELECT `treeEntity`.`video_category_id` AS `treeEntity_video_category_id`, `treeEntity`.`name` AS `treeEntity_name`, `treeEntity`.`type` AS `treeEntity_type`, `treeEntity`.`parentVideoCategoryId` AS `treeEntity_parentVideoCategoryId` FROM `category` `treeEntity` WHERE `treeEntity`.`parentId` IS NULL
error: { Error: ER_BAD_FIELD_ERROR: Unknown column 'treeEntity.parentId' in 'where clause'
    at Query.Sequence._packetToError (E:\WebstormProjects\summer-video-cms-service\node_modules\mysql\lib\protocol\sequences\Sequence.js:52:14)
    at Query.ErrorPacket (E:\WebstormProjects\summer-video-cms-service\node_modules\mysql\lib\protocol\sequences\Query.js:77:18)
    at Protocol._parsePacket (E:\WebstormProjects\summer-video-cms-service\node_modules\mysql\lib\protocol\Protocol.js:279:23)
    at Parser.write (E:\WebstormProjects\summer-video-cms-service\node_modules\mysql\lib\protocol\Parser.js:76:12)
    at Protocol.write (E:\WebstormProjects\summer-video-cms-service\node_modules\mysql\lib\protocol\Protocol.js:39:16)
    at Socket.<anonymous> (E:\WebstormProjects\summer-video-cms-service\node_modules\mysql\lib\Connection.js:103:28)
    at Socket.emit (events.js:182:13)
    at Socket.EventEmitter.emit (domain.js:442:20)
    at addChunk (_stream_readable.js:277:12)
    at readableAddChunk (_stream_readable.js:262:11)
    --------------------
    at Protocol._enqueue (E:\WebstormProjects\summer-video-cms-service\node_modules\mysql\lib\protocol\Protocol.js:145:48)
    at PoolConnection.query (E:\WebstormProjects\summer-video-cms-service\node_modules\mysql\lib\Connection.js:208:25)
    at MysqlQueryRunner.<anonymous> (E:\WebstormProjects\summer-video-cms-service\src\driver\mysql\MysqlQueryRunner.ts:146:36)
    at step (E:\WebstormProjects\summer-video-cms-service\node_modules\typeorm\driver\mysql\MysqlQueryRunner.js:42:23)
    at Object.next (E:\WebstormProjects\summer-video-cms-service\node_modules\typeorm\driver\mysql\MysqlQueryRunner.js:23:53)
    at fulfilled (E:\WebstormProjects\summer-video-cms-service\node_modules\typeorm\driver\mysql\MysqlQueryRunner.js:14:58)
    at process._tickCallback (internal/process/next_tick.js:68:7)
  code: 'ER_BAD_FIELD_ERROR',
  errno: 1054,
  sqlMessage: 'Unknown column \'treeEntity.parentId\' in \'where clause\'',
  sqlState: '42S22',
  index: 0,
  sql: 'SELECT `treeEntity`.`video_category_id` AS `treeEntity_video_category_id`, `treeEntity`.`name` AS `treeEntity_name`, `treeEntity`.`type` AS `treeEntity_type`, `treeEntity`.`parentVideoCategoryId` AS `treeEntity_parentVideoCategoryId` FROM `category` `treeEntity` WHERE `treeEntity`.`parentId` IS NULL' }

@pleerock

@pleerock
Copy link
Member

please provide a schema creation part (drop all tables and re-run)

@newcomein
Copy link
Author


query: START TRANSACTION
query: SELECT DATABASE() AS `db_name`
query: SELECT * FROM `INFORMATION_SCHEMA`.`TABLES` WHERE (`TABLE_SCHEMA` = 'summervideocms2' AND `TABLE_NAME` = 'user') OR (`TABLE_SCHEMA` = 'summervideocms2' AND `TABLE_NAME` = 'captcha') OR (`TABLE_SCHEMA` = 'summervideocms2' AND `TABLE_NAME` = 'category') OR (`TABLE_SCHEMA` = 'summervideocms2' AND `TABLE_NAME` = 'category_closure')
query: SELECT * FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE (`TABLE_SCHEMA` = 'summervideocms2' AND `TABLE_NAME` = 'user') OR (`TABLE_SCHEMA` = 'summervideocms2' AND `TABLE_NAME` = 'captcha') OR (`TABLE_SCHEMA` = 'summervideocms2' AND `TABLE_NAME` = 'category') OR (`TABLE_SCHEMA` = 'summervideocms2' AND `TABLE_NAME` = 'category_closure')
query: SELECT * FROM `INFORMATION_SCHEMA`.`KEY_COLUMN_USAGE` WHERE `CONSTRAINT_NAME` = 'PRIMARY' AND ((`TABLE_SCHEMA` = 'summervideocms2' AND `TABLE_NAME` = 'user') OR (`TABLE_SCHEMA` = 'summervideocms2' AND `TABLE_NAME` = 'captcha') OR (`TABLE_SCHEMA` = 'summervideocms2' AND `TABLE_NAME` = 'category') OR (`TABLE_SCHEMA` = 'summervideocms2' AND `TABLE_NAME` = 'category_closure'))
query: SELECT `SCHEMA_NAME`, `DEFAULT_CHARACTER_SET_NAME` as `CHARSET`, `DEFAULT_COLLATION_NAME` AS `COLLATION` FROM `INFORMATION_SCHEMA`.`SCHEMATA`
query: SELECT `s`.* FROM `INFORMATION_SCHEMA`.`STATISTICS` `s` LEFT JOIN `INFORMATION_SCHEMA`.`REFERENTIAL_CONSTRAINTS` `rc` ON `s`.`INDEX_NAME` = `rc`.`CONSTRAINT_NAME` WHERE ((`s`.`TABLE_SCHEMA` = 'summervideocms2' AND `s`.`TABLE_NAME` = 'user') OR (`s`.`TABLE_SCHEMA` = 'summervideocms2' AND `s`.`TABLE_NAME` = 'captcha') OR (`s`.`TABLE_SCHEMA` = 'summervideocms2' AND `s`.`TABLE_NAME` = 'category') OR (`s`.`TABLE_SCHEMA` = 'summervideocms2' AND `s`.`TABLE_NAME` = 'category_closure')) AND `s`.`INDEX_NAME` != 'PRIMARY' AND `rc`.`CONSTRAINT_NAME` IS NULL
query: SELECT `kcu`.`TABLE_SCHEMA`, `kcu`.`TABLE_NAME`, `kcu`.`CONSTRAINT_NAME`, `kcu`.`COLUMN_NAME`, `kcu`.`REFERENCED_TABLE_SCHEMA`, `kcu`.`REFERENCED_TABLE_NAME`, `kcu`.`REFERENCED_COLUMN_NAME`, `rc`.`DELETE_RULE` `ON_DELETE`, `rc`.`UPDATE_RULE` `ON_UPDATE` FROM `INFORMATION_SCHEMA`.`KEY_COLUMN_USAGE` `kcu` INNER JOIN `INFORMATION_SCHEMA`.`REFERENTIAL_CONSTRAINTS` `rc` ON `rc`.`constraint_name` = `kcu`.`constraint_name` WHERE (`kcu`.`TABLE_SCHEMA` = 'summervideocms2' AND `kcu`.`TABLE_NAME` = 'user') OR (`kcu`.`TABLE_SCHEMA` = 'summervideocms2' AND `kcu`.`TABLE_NAME` = 'captcha') OR (`kcu`.`TABLE_SCHEMA` = 'summervideocms2' AND `kcu`.`TABLE_NAME` = 'category') OR (`kcu`.`TABLE_SCHEMA` = 'summervideocms2' AND `kcu`.`TABLE_NAME` = 'category_closure')
query: CREATE TABLE `user` (`user_id` varchar(255) NOT NULL COMMENT '唯一id', `userName` varchar(255) NOT NULL COMMENT '用户名', `email` varchar(255) NOT NULL COMMENT '邮箱', `avatar` varchar(255) NOT NULL COMMENT '头像', `password` varchar(255) NOT NULL COMMENT '密码', `sex` enum ('0', '1') NOT NULL COMMENT '女,男', `addTime` datetime NOT NULL COMMENT '添加时间', `updateTime` datetime NULL COMMENT '更新时间', `loginTime` datetime NULL COMMENT '登录时间', `lastLoginTime` datetime NULL COMMENT '上次登录时间', PRIMARY KEY (`user_id`)) ENGINE=InnoDB
query: CREATE TABLE `captcha` (`captcha_id` varchar(255) NOT NULL COMMENT '唯一id', `user_id` varchar(255) NULL COMMENT '唯一id', `email` varchar(255) NOT NULL COMMENT '邮箱', `cipherText` varchar(255) NOT NULL COMMENT '验证码密文', `type` enum ('0', '1') NOT NULL COMMENT 'emailCode,svgCaptchaCode', `addTime` datetime NOT NULL COMMENT '添加时间', UNIQUE INDEX `REL_b7b5128be4343810eee1f7d9ff` (`user_id`), PRIMARY KEY (`captcha_id`)) ENGINE=InnoDB
query: CREATE TABLE `category` (`video_category_id` varchar(255) NOT NULL COMMENT '唯一id', `name` varchar(255) NOT NULL COMMENT '菜单名', `type` enum ('0', '1') NOT NULL COMMENT '视频分类,未定义的分类', `parentVideoCategoryId` varchar(255) NULL COMMENT '唯一id', PRIMARY KEY (`video_category_id`)) ENGINE=InnoDB
query: CREATE TABLE `category_closure` (`video_category_id_ancestor` varchar(255) NOT NULL, `video_category_id_descendant` varchar(255) NOT NULL, PRIMARY KEY (`video_category_id_ancestor`, `video_category_id_descendant`)) ENGINE=InnoDB
query: ALTER TABLE `captcha` ADD CONSTRAINT `FK_b7b5128be4343810eee1f7d9ff5` FOREIGN KEY (`user_id`) REFERENCES `user`(`user_id`)
query: ALTER TABLE `category` ADD CONSTRAINT `FK_00c41e95fcf62768433f064153c` FOREIGN KEY (`parentVideoCategoryId`) REFERENCES `category`(`video_category_id`)
query: ALTER TABLE `category_closure` ADD CONSTRAINT `FK_50eb98c58983a8c64df2861a7a0` FOREIGN KEY (`video_category_id_ancestor`) REFERENCES `category`(`video_category_id`)
query: ALTER TABLE `category_closure` ADD CONSTRAINT `FK_4b635b55949244bade68b4be51e` FOREIGN KEY (`video_category_id_descendant`) REFERENCES `category`(`video_category_id`)
query: COMMIT

@pleerock

@artem-hryb
Copy link

artem-hryb commented Jul 16, 2018

I met the same issue on 'finRoots' call. The reason of this is that your Category entity has 'video_category_id' primary key instead of 'id'. Rename the 'video_category_id' to 'id' will fix the problem.

It appears that TypeOrm in your case creates column as 'parentVideo_category_id' in category table. But during the call 'finRoots' tries to consume not existed 'parentId' (it is string concatenation 'parent'+'Id' but typeorm should use 'parent'+ 'Video_category_id' instead). So it is bug.

@newcomein

This comment has been minimized.

@pleerock

This comment has been minimized.

@LogansUA
Copy link

LogansUA commented Aug 1, 2018

@pleerock Hi, I'm facing similar issue. I have custom naming strategy, so columns in DB are underscored

naming-strategy.ts
import { DefaultNamingStrategy, NamingStrategyInterface } from "typeorm";
import { snakeCase } from "typeorm/util/StringUtils";

export class NamingStrategy extends DefaultNamingStrategy implements NamingStrategyInterface {
    public tableName(targetName: string, userSpecifiedName: string): string {
        return userSpecifiedName ? userSpecifiedName : snakeCase(targetName);
    }

    public columnName(propertyName: string, customName: string, embeddedPrefixes: Array<string>): string {
        return snakeCase(embeddedPrefixes.concat(customName ? customName : propertyName).join("_"));
    }
}

Here's my entity:

geo.ts
import { Column, CreateDateColumn, Entity, Index, JoinColumn, OneToMany, PrimaryGeneratedColumn, Tree, TreeChildren, TreeParent } from "typeorm";

@Entity({
    name: "geo",
})
@Tree("materialized-path")
export class Geo {
    @PrimaryGeneratedColumn("uuid")
    public id: string;

    @Column()
    @Index({ unique: true })
    public code: string;

    @Column()
    @Index({ unique: true })
    public name: string;

    @TreeParent()
    public parent: Geo;

    @TreeChildren()
    public children: Array<Geo>;

    @CreateDateColumn({
        name: "created_at",
    })
    public createdAt: Date;
}

So in my DB columns are underscored (i.e. parent_id) but query appears to call parentId.
Error:

query: SELECT "treeEntity"."id" AS "treeEntity_id", "treeEntity"."code" AS "treeEntity_code", "treeEntity"."name" AS "treeEntity_name", "treeEntity"."mpath" AS "treeEntity_mpath", "treeEntity"."parent_id" AS "treeEntity_parent_id" FROM "geo" "treeEntity" WHERE "treeEntity"."parentId" IS NULL
query failed: SELECT "treeEntity"."id" AS "treeEntity_id", "treeEntity"."code" AS "treeEntity_code", "treeEntity"."name" AS "treeEntity_name", "treeEntity"."mpath" AS "treeEntity_mpath", "treeEntity"."parent_id" AS "treeEntity_parent_id" FROM "geo" "treeEntity" WHERE "treeEntity"."parentId" IS NULL
error: { error: column treeEntity.parentId does not exist
    at Connection.parseE (/path/to/project/node_modules/pg/lib/connection.js:553:11)
    at Connection.parseMessage (/path/to/project/node_modules/pg/lib/connection.js:378:19)
    at Socket.<anonymous> (/path/to/project/node_modules/pg/lib/connection.js:119:22)
    at emitOne (events.js:116:13)
    at Socket.emit (events.js:211:7)
    at addChunk (_stream_readable.js:263:12)
    at readableAddChunk (_stream_readable.js:250:11)
    at Socket.Readable.push (_stream_readable.js:208:10)
    at TCP.onread (net.js:597:20)
  name: 'error',
  length: 185,
  severity: 'ERROR',
  code: '42703',
  detail: undefined,
  hint: 'Perhaps you meant to reference the column "treeEntity.parent_id".',
  position: '321',
  internalPosition: undefined,
  internalQuery: undefined,
  where: undefined,
  schema: undefined,
  table: undefined,
  column: undefined,
  dataType: undefined,
  constraint: undefined,
  file: 'parse_relation.c',
  line: '3293',
  routine: 'errorMissingColumn' }

As you can see, the where part of query is wrong.

Is there some way to force @Tree use custom field name?

It would be great, if we could specify in @TreeParent the custom field name. Or somehow configure @Tree to use custom name from @JoinColumn decorator.

Which defined similar to this

    @TreeParent()
    @JoinColumn({
        name: "parent_id",
    })
    public parent: Geo;

It's actually really critical to me so if you could help me I would be really thankful.

@LogansUA
Copy link

@pleerock any thoughts on it?

@isomeruk
Copy link

Just adding my +1 to this issue. Exactly the same problem as @LogansUA.

...
query failed: SELECT `treeEntity`.`id` AS `treeEntity_id`, `treeEntity`.`valid_from` AS `treeEntity_valid_from`, `treeEntity`.`valid_to` AS `treeEntity_valid_to`, `treeEntity`.`category_name` AS `treeEntity_category_name`, `treeEntity`.`mpath` AS `treeEntity_mpath`, `treeEntity`.`creator_id` AS `treeEntity_creator_id`, `treeEntity`.`destroyer_id` AS `treeEntity_destroyer_id`, `treeEntity`.`organization_id` AS `treeEntity_organization_id`, `treeEntity`.`parent_category_id` AS `treeEntity_parent_category_id` FROM `product_category` `treeEntity` WHERE `treeEntity`.`parentCategoryId` IS NULL
...

Although not as critical as I can rename the column, it would be nice to be able to keep column names consistent.

@pleerock
Copy link
Member

pleerock commented Jan 4, 2019

Since there are multiple reports I'll mark it as a bug but we still need some tests before we fix it.

@hypeofpipe
Copy link

Any updates on this?

ruciu added a commit to ruciu/typeorm that referenced this issue Aug 20, 2019
Create failing test for typeorm#2361 when id name in parent id different than id
@ruciu
Copy link

ruciu commented Aug 20, 2019

@pleerock
I created failing test for this issue, and I can also try to fix this issue. Do you have any decorator you would prefer to modify in order to add this custom id name?

ruciu added a commit to ruciu/typeorm that referenced this issue Aug 26, 2019
Updated test for typeorm#2361 with custom migrations
ruciu added a commit to ruciu/typeorm that referenced this issue Aug 26, 2019
@bmoe24x
Copy link

bmoe24x commented Sep 19, 2019

Same issue! It deletes columns out of my database even with 'synchronize' off, not cool!

@AlexPanacea
Copy link

Using an existing MySQL Database with custom fields too, would be great to be able to use custom field name, my query searches for field 'UserGuid' instead of just 'user'.

@viablecell
Copy link

@LogansUA
add code below to your naming-strategy.ts

joinColumnName(relationName: string, referencedColumnName: string): string {
    return snakeCase(relationName + '_' + referencedColumnName);
}

@imnotjames
Copy link
Contributor

I think this is related to #1668 ? Difficult to tell.

@Jood80
Copy link

Jood80 commented Jul 21, 2021

any updates on that?

@thexeos
Copy link

thexeos commented Dec 11, 2021

Here is another example of this not working (using SnakeNamingStrategy):

const query = getRepository(SomeEntity)
  .createQueryBuilder('someEntity')
  .delete()
  .where('someEntity.anything = :val', { val })

console.log(query.getQueryAndParameters())
//  [ 'DELETE FROM `some_entity` WHERE someEntity.anything = ?', [ "val" ] ]

Which results in somewhat misleading QueryFailedError: Unknown column 'someEntity.anything' in 'where clause', as you first assume you got column name wrong and not table name.

@hongdor
Copy link

hongdor commented Dec 22, 2021

any updates on that? I have simillar issue,,,

@Entity()
@Tree("closure-table", {
    closureTableName: "place",        
    ancestorColumnName: (column) => "ancestor_id",
    descendantColumnName: (column) => "descendant_id"
})
export class Place {
    
    @PrimaryGeneratedColumn()
    placeId: number;
    
    @TreeParent()     
    @JoinColumn({name : "parent_id"})
    parent: Place;   

    @TreeChildren()
    children: Place[];
}
async findOneRootTreeWithTagValues(place){        
        const manager = await getManager();
        const trees = await manager.getTreeRepository(Place).findDescendantsTree(place)
}
QueryFailedError: ER_BAD_FIELD_ERROR: Unknown column 'treeEntity.placeId' in 'on clause'

@bttger
Copy link

bttger commented Mar 19, 2022

Here is another example of this not working (using SnakeNamingStrategy)

I can confirm this. E.g. I have a file car-dealer.entity.ts with the entity CarDealer.

const query = getRepository(CarDealer)
  .createQueryBuilder('carDealer')
  .delete()
  .where('carDealer.id = :id', { id });

console.log(qb.getQueryAndParameters());
// [  'DELETE FROM `car_dealer` WHERE carDealer.id = ?',  [ 'xxxxxx' ] ]

// Leads to "QueryFailedError: Unknown column 'carDealer.id' in 'where clause'"

However, it works fine when using single words (without dashs or snake case) as entities.

It seems that the alias just gets ignored/not set in the query.

@evanlong0803
Copy link

I made a similar mistake:Unknown column 'treeEntity.id' in 'on clause'

@odavibatista
Copy link

Had the same issue using TypeORM + NestJs, and ended that it was a problem of giving the params for the route itself. My "@param('id')" was without the 'id', so it was understanding it as an object, not as a numeric value.

 async findOne(
        @Param('id') id: number,
        @Req() req: Request,
        @Res() res: Response,
    ): Promise<FindJobResponseDTO | JobNotFoundException | AllExceptionsFilterDTO>  {
        const result = await this.jobService.findOne(id);

        if (result instanceof HttpException) {
            return res.status(result.getStatus()).json({
              message: result.message,
              status: result.getStatus(),
            });
          } else {
            return res.status(res.statusCode).json(result);
          }
    }

@thd0
Copy link

thd0 commented May 28, 2024

any updates on that? I have simillar issue,,,

@Entity()
@Tree("closure-table", {
    closureTableName: "place",        
    ancestorColumnName: (column) => "ancestor_id",
    descendantColumnName: (column) => "descendant_id"
})
export class Place {
    
    @PrimaryGeneratedColumn()
    placeId: number;
    
    @TreeParent()     
    @JoinColumn({name : "parent_id"})
    parent: Place;   

    @TreeChildren()
    children: Place[];
}
async findOneRootTreeWithTagValues(place){        
        const manager = await getManager();
        const trees = await manager.getTreeRepository(Place).findDescendantsTree(place)
}
QueryFailedError: ER_BAD_FIELD_ERROR: Unknown column 'treeEntity.placeId' in 'on clause'

I have the similar issue today and I solved it by changing PrimaryColumn to snake_case and problem solved.

    @PrimaryColumn({ name: "user_id" })
-    userId: number;
+    user_id: number;

Also, since the product is already released, to avoid having to write a database migration, I also add the following line for the ancestor and descendant columns with the previous names from the database (something I should have done from the beginning).

-  @Tree("closure-table")
+  @Tree("closure-table", {
+    ancestorColumnName: () => "userId_ancestor",
+    descendantColumnName: () => "userId_descendant"
+  })

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests