MA-Moustache
MA-Moustache

Reputation: 335

Many to many relations aren't showing in database

Good morning!

Here is my code, the problem is written just below the code This is a many to many relation where user can subscribe to item

user.entity.ts

@Entity("user")
export class UserEntity {

    @PrimaryGeneratedColumn('uuid')
    id: string;

    @Column({
        type: 'varchar',
        length: 50,
        unique: true,
    })
    username: string;

    @Column('text')
    password: string;

    @Column('text')
    role: string;

    @OneToMany(type => SubscriptionEntity, subscriptionEntity => subscriptionEntity.user)
    subscription: SubscriptionEntity[];
}

item.entity.ts

@Entity("item")
export class ItemEntity {

    constructor() {}

    @PrimaryGeneratedColumn() id: number;

    @Column('text') name: string;

    @Column('text') description: string;

    @Column('decimal') price: number;

    @Column('text') picture: string;

    @OneToMany(type => SubscriptionEntity, subscriptionEntity => subscriptionEntity.item)
    subscription: SubscriptionEntity[];
}

subscription.entity.ts

@Entity("subscription")
export class SubscriptionEntity {

    @PrimaryColumn() userId: string;
    @PrimaryColumn() itemId: number;

    @ManyToOne(type => UserEntity, user => user.subscription)
    @JoinColumn({name: "userId"})
    user: UserEntity;

    @ManyToOne(type => ItemEntity, item => item.subscription)
    @JoinColumn({name: "itemId"})
    item : ItemEntity;
}

The problem is that my relations / foreign keys are not showing in my database:

desc subscription

+--------+--------------+------+-----+---------+-------+
| Field  | Type         | Null | Key | Default | Extra |
+--------+--------------+------+-----+---------+-------+
| userId | varchar(255) | NO   | PRI | NULL    |       |
| itemId | int(11)      | NO   | PRI | NULL    |       |
+--------+--------------+------+-----+---------+-------+

I really can't see the problem there. I sticked closely to this LINK and on the full bottom you can see pretty much the same code.

Upvotes: 0

Views: 71

Answers (1)

kierans
kierans

Reputation: 2213

Given you want userId and itemId to be foreign keys to their tables (User and Item respectively) you shouldn't define them as primary keys. On the SubscriptionEntity just have an autogenerated ID as the primary key.

However if you want to enforce a single subscription of an item to a user, you can use a Unique constraint eg: @Unique(["user", "item"])

Upvotes: 1

Related Questions