Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeORM: How to set ForeignKey explicitly without having property for loading relations?

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?

like image 708
Sergei Avatar asked Mar 14 '19 19:03

Sergei


1 Answers

"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;
like image 148
charles Avatar answered Sep 21 '22 12:09

charles