DEV Community

Discussion on: Day 48: Defining Relations using TypeORM

Collapse
 
elthrasher profile image
Matt Morgan

Right, in the function post => post.user what it's asking is "what is the property on the entity I have a relationship with that points back to this entity?" In this case it is "I am a User and I have a relationship to Post. What property on Post represents me?"

In post => post.user post is just the name of the property TypeORM automatically passes in to figure out these relationships (so it could be foo => foo.user and would work the same). Part of the reason for this is you could have complicated mappings, like maybe instead of Post just having a User, presumably the User who wrote the Post, you could have Post having two different relationships with User, the original author and most recent editor. They can both have relationships with the same User entity, but will be different properties:

@Entity() 
class Post {
  @PrimaryGeneratedColumn()
  public postId: string; 

  @ManyToOne( type => User, user => user.editedPosts)
  editedBy: User;

  @ManyToOne( type => User, user => user.authoredPosts)
  writtenBy: User;
}
Enter fullscreen mode Exit fullscreen mode

Not sure that's the best design, but it'll give you an idea of more complex relationships.

Yeah posts: Post[] would indicate that the user has a relationship with many posts that would be mapped into an array if you executed the join query. By default the join query isn't executed so you'd need to specify an eager join or use a join relationship in the query builder to actually populate all the posts.

BTW a really good option when learning or debugging TypeORM is to enable logging in connection options. Any time you use an ORM it's important to connect the models to the SQL they eventually produce and TypeORM has a really good logger that will help you do that.

Thread Thread
 
mtee profile image
Margaret W.N

Woow, it is so clear right now. Thank you for taking your time to explain it to me. I'll jump right into it and expound on the topics you've linked. Very much appreciated 🙏.