Search code examples
mysqltypeorm

One to one relationship using Typeorm and MySQL


guys! Today I'm trying to create a One-To-One relationship for my GraphQL API using TypeORM. I've followed the example from here: https://orkhan.gitbook.io/typeorm/docs/one-to-one-relations because I want to create almost the same thing as that example (That with the user and the profile.). The fact is that I have a Users table and a UserActions table. Every user should have a row in the UserAction table. The problem is that I want to be able to delete the UserAction just if I deleted the User. I also want to use the cascade option, and when I'll delete a user, the UserActions row to be deleted aswell.

I've added this in the User entity:

@OneToOne(() => UserAction)
@JoinColumn()
userActions!: UserAction;

Is there anything else to do for the behaviour I described? The problem is that if I let it like this, I will be able to delete the UserAction, and the User to be also available in the database. That's not what I want, and as I said, I also want the UserAction to be deleted just when I also delete the User. I hope that I explained my issue well. If you have any other questions, feel free to comment. Thanks for your help!


Solution

  • If you want the user action to be deleted when the user is deleted, then you can use this:

    @OneToOne(() => UserAction, { onDelete: 'CASCADE' })
    @JoinColumn()
    userActions!: UserAction;
    

    UPDATE:

    Based on your comment, if you want the user to be deleted when the user action is deleted, you can follow the same principle as the above. See the below example:

    export class UserAction {
      @OneToOne(() => User, { onDelete: 'CASCADE' })
      @JoinColumn()
      user!: User;
    
      // Other properties
      ...
    }
    

    Make sure you have @JoinColumn on only one side of the relationship.


    In SQL, one-to-one relationships, cascade delete will be applied to the child. Meaning, if the parent is deleted, the child will be deleted. But if the child is deleted, the parent will not be deleted.

    If I am not wrong, Typeorm follows the same principle. Therefore, if you need to have cascade deletion on both sides, I don't think that is possible in Typeorm.