Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Composite primary key in MySQL typeORM

Tags:

typeorm

I need to create a composite primary key. I have two entities are user and task.

User entity

@Entity('users')
export class User extends BaseEntity {
    @PrimaryGeneratedColumn('uuid')
    public readonly id: string;

    @Column({ nullable: false, type: 'varchar', length: 16 })
    public readonly name: string;

    @OneToMany(() => Task, (task: Task) => task.user)
    public readonly tasks: Task[];
}

Task entity

@Entity('tasks')
export class Task extends BaseEntity {
    @PrimaryGeneratedColumn('uuid')
    public readonly id: string;

    @Column({ nullable: true, type: 'varchar', length: 16 })
    public readonly name: string;

    @Column({ type: 'varchar', nullable: false })
    public readonly userId: string;

    @ManyToOne(() => User, (user: User) => user.tasks)
    @JoinColumn({ name: 'userId' })
    public readonly user: User;
}

In my table task I have to use a composite primary key. For example 4a00a3738e90e-0007. It's user id '4a00a3738e90e' and it's '0007' count task of user.

How can I create composite primary key? I didn't find a decision in the documentation.

id                      name    userId
4a00a3738e90e-0001      task1   4a00a3738e90e
4a00a3738e90e-0002      task2   4a00a3738e90e
1er04r35l56en-0001      task1   1er04r35l56en
like image 861
MegaRoks Avatar asked Nov 06 '22 04:11

MegaRoks


1 Answers

If you are trying to get the number 1 from 'task1', convert this to 0001 and use it as part of your key, shouldn't this be more of a task for your web application? Generate it first and insert it into your database.

If you are trying to have the composite key consisting of two columns, I would just set 'userId' and a 'taskCount' as the the composite primary key, which I think is the better solution here. Maybe something like this:

@ManyToOne(() => User, (user: User) => user.tasks, {primary: true})
@JoinColumn({ name: 'userId' })
public readonly user: User;   

@PrimaryColumn({type: "integer"})
public taskCount: number;    
like image 78
BlueIceZ Avatar answered Nov 24 '22 08:11

BlueIceZ