Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

I don't want to create a property for loading relation into it (as shown in all the examples). The only thing I need is to have an explicit foreign key property so that the migration will be able to create appropriate constraints for it in the database. The closest decorator to the one I need is @RelationId but it still requires the presence of a property of the relational class.

For clarity let's take the example from the documentation:

@Entity()
export class Post {
    @ManyToOne(type => Category)
    category: Category;
    @RelationId((post: Post) => post.category) // it still requires the presence of the `category` proeprty
    categoryId: number;

I don't need the category property here. I want to have the categoryId property and mark it as foreign key to Category.Id. It should look like this:

@Entity()
export class Post {
    @ForeignKey((category: Category) => category.Id) // it's a foreign key to Category.Id
    categoryId: number;

Is it possible?

Sorry, man, I've changed my tech stack a year ago. I believe I didn't find a way around at the time. – Serg Jun 1, 2020 at 13:39

"I need is to have an explicit foreign key property"...

No, you could not. TypeOrm will automatically create foreign key property when you use @ManyToOne decorator. Just combine @ManyToOne and @JoinColumn decorators together like this:

@ManyToOne(type => Category)
@JoinColumn({ name: 'custom_field_name_if_you_want' })
category: Category;

Maybe you can create and write your own migration and use it like this :

    const queryRunner = connection.createQueryRunner();
    await queryRunner.createTable(new Table({
        name: "question",
        columns: [
                name: "id",
                type: "int",
                isPrimary: true
                name: "name",
                type: "varchar",
    }), true);
    await queryRunner.createTable(new Table({
        name: "answer",
        columns: [
                name: "id",
                type: "int",
                isPrimary: true
                name: "name",
                type: "varchar",
                name: "questionId",
                isUnique: connection.driver instanceof CockroachDriver, // CockroachDB requires UNIQUE constraints on referenced columns
                type: "int",
    }), true);
    // clear sqls in memory to avoid removing tables when down queries executed.
    queryRunner.clearSqlMemory();
    const foreignKey = new TableForeignKey({
        columnNames: ["questionId"],
        referencedColumnNames: ["id"],
        referencedTableName: "question",
        onDelete: "CASCADE"
    await queryRunner.createForeignKey("answer", foreignKey);

This code snippet is extracted from the functional test of type orm and you can use it to create your own constraint on the database I think.

// and you can use this for accessing post.categoryId // only column you mark with @Column decorator will be mapped to a database column // Ref: https://typeorm.io/#/entities categoryId: number;

The added categoryId won't be mapped to column and will then be use for setting explicitly the id or for accessing its value as in:

 post.categoryId = 1;
 // or 
 const id = post.categoryId
                I think the categoryId needs the Column Decorator =>  @Column({ nullable: false }) github.com/typeorm/typeorm/issues/156#issuecomment-269579837
– Simon Sheep
                Mar 18 at 8:56

I have encountered the same problem recently. I still use the Entity but only with the primary key value of the referenced entity.

i.e. I do not query the database for the referenced entity.

Suppose your category entity looks like this:

@Entity()
export class Category{
    @PrimaryGeneratedColumn()
    id: number;
    // ... other stuff

Now using your codes as example. Dircely assigning relation using a foreign key value would be like.

// You wish to assign category #12 to a certain post
post.category = { id: 12 } as Category
                Hi @Sunny Tare, remember to use block code format to make your code easier to read in your answer
– Cohen
                Jan 12, 2021 at 0:45
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.