typeform按字符串插入外键



当用户注册时,我希望他发送他的帐户名,所以我将有"Accounts"表中引用的用户实体。我用的是Nest.js。我正在寻找替代以下逻辑在我的users.service.ts寄存器方法:

  1. 按名称查找帐户
  2. 如果没有找到帐户,创建它
  3. 使用上面找到的帐户创建用户

这是我的帐户实体:

@Entity()
export class Account extends BaseEntity {
@PrimaryGeneratedColumn('uuid')
id: string;

@Column({ unique: true })
name: string;

@Column()
@CreateDateColumn()
createdAt: Date;
}

和我的用户实体:

@Entity() 
export class User extends BaseEntity {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column({ unique: true })
email: string;
@Column()
password: string;
@ManyToOne(() => Account, (Account) => Account.name, { cascade:true })
@JoinColumn({name: 'name'})
account: Account;
}

我CreateUserDTO:

export class CreateUserDto {
@IsEmail()
email: string;
@IsNotEmpty()
password: string;
@IsNotEmpty()
account: string;
}

这是错误时,我试图做User.create(dto):Type 'string' is not assignable to type 'Account | DeepPartial<Account>'.

另外,由于某种原因,User.create(dto)返回用户数组而不是单个用户,我不明白为什么。

你可以这样做:

// create-user.dto.ts
export class CreateUserDto {
@IsEmail()
email: string;
@IsString()
@IsNotEmpty()
password: string;
@IsString()
@IsNotEmpty()
accountName: string;
}

@Entity()
export class User extends BaseEntity {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column({ unique: true })
email: string;
@Column()
password: string;
@Column()
name: string; // This is your relations between user and account defined in JoinColumn decorator
@ManyToOne(() => Account, (Account) => Account.name, { cascade: true })
@JoinColumn({ name: 'name' })
account: Account;
}
// user.service.ts
// user.service.ts
@Injectable()
export class UserService {
constructor(
@InjectRepository(Account)
private readonly accountRepository: Repository<Account>, // Or your custom repository
@InjectRepository(User)
private readonly userRepository: Repository<User> // Or your custom repository
) {}
public async register(dto: CreateUserDto): Promise<void> {
let accountToSaveWithUser: Account;
// First check if account exist
const account = await this.accountRepository.findOne({
where: {
name: dto.accountName,
},
});
if (isNil(account)) {
const accountToSave = this.accountRepository.create({
name: dto.accountName,
});
accountToSaveWithUser = await this.accountRepository.save(accountToSave);
} else {
accountToSaveWithUser = account;
}
await this.userRepository.save({
email: dto.email,
password: hash(dto.password), // Use your package for hash password
name: accountToSaveWithUser.name,
});
}
}

最新更新