我有两个实体
用户:
@Entity()
export class Users {
@PrimaryGeneratedColumn()
user_id: number;
@OneToOne(_ => UserContacts, contact => contact.user_id)
@JoinColumn({ name: 'contact_id' })
contacts: UserContacts
}
@Entity()
export class UserContacts {
@PrimaryGeneratedColumn()
contact_id: number;
@OneToOne(_ => Users, users => users.contacts)
user_id: Users;
}
但在PostgreSQL保存后,我有:
user_contacts表:
contact_id | user_id
------------+---------
6 |
users表:
user_id | contact_id
---------+------------
7 | 6
我想在user_contacts表中user_id列应该是7
我只学习TypeORM所以我不创建任何架构
我有两个函数用于创建联系人和用户
我的保存流程:
export function createUser(contacts?: UserContacts): Users {
const user = new Users();
user.firstName = faker.name.firstName();
user.lastName = faker.name.lastName();
user.age = faker.datatype.number({ min: 1, max: 99 });
if (contacts) { user.contacts = contacts }
return user
}
export function createContacts(): UserContacts {
const contact = new UserContacts()
contact.email = faker.internet.email();
contact.phone = faker.phone.phoneNumber('##########');
contact.address = faker.address.city();
return contact;
}
async function bootstrap() {
try {
const connection = await createConnection();
const userRepository = connection.getRepository(Users);
const contactRepository = connection.getRepository(UserContacts);
const contacts = createContacts();
const user = createUser(contacts);
contactRepository.save(contacts);
userRepository.save(user);
console.info('Done!');
} catch (e) {
console.error(e.message);
}
}
bootstrap();
我做错了什么?
没有JoinColumn的OneToOne装饰器,TypeORM使用它作为双向关系的元数据
@Entity()
export class UserContacts {
@PrimaryGeneratedColumn()
contact_id: number;
// This property is metadata. It's not column for DB
@OneToOne(_ => Users, users => users.contacts)
user: Users;
}