我目前正在尝试使用不使用 Typescript 的 TypeORM 创建多对一
和一对多
关系。
我有以下实体设置:
./entity/proposal
module.exports = {
name: "Proposal",
columns: {
id: {
primary: true,
type: "int",
generated: true
},
name: {
type: "varchar",
length: 60
},
description: {
type: "varchar",
default: "",
length: 150
},
createdAt: {
createDate: true
},
updatedAt: {
updateDate: true
}
},
relations: {
sections: {
target: "Section",
type: "one-to-many",
treeParent: true,
cascade: true,
inverseSide: 'Proposal'
}
}
}
./entity/section
module.exports = {
name: "Section",
columns: {
id: {
primary: true,
type: "int",
generated: true
},
name: {
type: "varchar",
length: 60,
default: "New Section"
},
order: {
type: "int"
}
},
relations: {
proposal: {
target: "Proposal",
type: "many-to-one",
joinColumn: true,
nullable: false
}
}
}
从这里我创建了两个函数,一个用于插入提议,另一个函数用于创建模拟数据,该模拟数据使用级联功能插入行(按照本例:https://github.com/typeorm/javascript-example)
./controller/createProposal.js
const getRepository = require('typeorm').getRepository
const createProposal = async proposal => {
let proposalRepository = getRepository("Proposal");
let result = await proposalRepository.save(proposal)
.then( savedProposal => {
return savedProposal
})
.catch( err => {
return {
message: "There was an issue saving the proposal",
err: err
}
});
return result
}
module.exports = createProposal
./controller/mockData.js
const createProposal = require('../proposal/createProposal')
const insertMockData = async () => {
let section1 = {
name: "Letter",
order: 1
}
let section2 = {
name: "Cloud",
order: 2
}
let proposal = {
name: "Cloud Proposal",
description: "Cloud Proposal",
sections: [
section1, section2
]
}
let result = await createProposal(proposal)
}
module.exports = insertMockData
将 insertMockData()
函数与 nullable: true
一起使用会产生以下结果:
=== Proposal Table ===
id name description
1 "Cloud Proposal" "Cloud Proposal"
=== Section Table ===
id name order proposalid
1 "Letter" 1 null
2 "Cloud" 2 null
我需要在节表中显示 proposalid
以便我可以使用 proposalRepository.findOneOrFail({ id , relations: ['sections'] }) 急切地找到它
.
我做错了什么?
最佳答案
尝试将eager: true
添加到Section->proposal
relations: {
proposal: {
target: "Proposal",
type: "many-to-one",
joinColumn: true,
nullable: false,
eager: true // This line
}
}
https://stackoverflow.com/questions/54145980/