当我开始为数据库添加种子时,一切都很好,但是当我尝试向同一用户的第二个列表中添加第二批商品时(第一类商品已成功添加到用户的第一列表中)
/entity/User.ts
@Entity('users') // @note for postgres naming conflict
export class User extends BaseEntity {
@PrimaryGeneratedColumn() id: number
@Column({ type: 'text', unique: true })
username: string
@OneToMany(() => Listing, listing => listing.user)
listings: Listing[]
}
/entity/Listing.ts 用户=> 1:M =>列表
@Entity()
export class Listing extends BaseEntity {
@PrimaryGeneratedColumn() id: number
@Column({ type: 'varchar', length: 255 })
title: string
@OneToMany(() => Offer, offer => offer.listing)
offers: Offer[]
@PrimaryColumn()
userId: number
@ManyToOne(() => User, user => user.listings)
@JoinColumn({ name: 'userId' })
user: Promise<User>
}
/entity/Offer.ts 列表=> 1:M =>提供
@Entity()
export class Offer extends BaseEntity {
@PrimaryGeneratedColumn() id: number
@Column('int') price: number
@PrimaryColumn()
listingId: number
@ManyToOne(() => Listing, listing => listing.offers)
@JoinColumn({ name: 'listingId' })
listing: Promise<Listing>
}
这里是用于播种db的代码的保证:
const users = [
{
id: 1,
username: faker.internet.userName(),
}
]
const listings = [
{
id: 1,
title: faker.lorem.sentence(),
userId: 1
},
{
id: 2,
title: faker.lorem.sentence(),
userId: 1,
}
]
const offers = [
{
id: 1,
price: faker.random.number(priceOptions),
listingId: 1,
},
{
id: 2,
price: faker.random.number(priceOptions),
listingId: 2,
}
]
export const startSeeding = async () => {
await users.map(user => User.create(user).save())
await listings.map(listing => Listing.create(listing).save())
setTimeout(async () => {
await offers.map(offer => Offer.create(offer).save())
}, 3000) // for sure
}
错误消息:
query failed: INSERT INTO "offer"("price", "wage", "hoursOfWeek", "housing", "tips", "overtimes", "notes", "offerTypeId", "positionId", "listingId") VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) RETURNING "id", "housing", "tips", "overtimes" -- PARAMETERS: [256,16,32,true,true,true,"Qui dolores assumenda doloremque doloribus.",1,2,2]
error: { error: insert or update on table "offer" violates foreign key constraint "FK_d33dccabb2f699c92920ff197c8"
detail: 'Key (listingId, listingId, listingId)=(2, 2, 2) is not present in table "listing".',
答案 0 :(得分:1)
await users.map(user => User.create(user).save())
错了
你应该做
await Promise.all(users.map(user => User.create(user).save()))
答案 1 :(得分:0)
我弄清楚了代码的问题,我将PrimaryColumn
用于1:M关系,但我只需要一个Column