mysql - 在连接表中插入附加数据
问题描述
我正在使用 express 构建一个应用程序,并且我使用 bookshelf (mysql) js 作为 ORM。我有一个多对多的关系,我试图在连接表中存储一些额外的数据。
我的模型:
const Product = Bookshelf.Model.extend({
tableName: 'products',
factors() {
return this.belongsToMany('Factor', 'product_factors', 'product_id', 'factor_id')
}
})
const Factor = Bookshelf.Model.extend({
tableName: 'factors',
products() {
return this.belongsToMany('Product')
}
})
在“product_factors”表中创建具有关系的新产品。
/** Create product */
router.route('/').post((req, res) => {
new Product({name: req.body.name})
.save()
.then(product => {
// attaching relation
product.factors().attach([3, 5])
.then(hz => {
res.status(201).json({
message: 'Product created'
})
})
})
})
“product_factors”表
|ID|product_id|factor_id|quantity|
|--|----------|---------|--------|
|1 |10 |3 |NULL |
|2 |10 |5 |NULL |
如何在附加关系的同时插入数量?
解决方案
该文档在model.belongsToMany()
部分中提供了如何执行此操作的示例。为方便起见,这里是:
let Doctor = bookshelf.Model.extend({
patients: function() {
return this.belongsToMany(Patient).through(Appointment);
}
});
let Appointment = bookshelf.Model.extend({
patient: function() {
return this.belongsTo(Patient);
},
doctor: function() {
return this.belongsTo(Doctor);
}
});
let Patient = bookshelf.Model.extend({
doctors: function() {
return this.belongsToMany(Doctor).through(Appointment);
}
});
正如您在Doctor
和Patient
模型中看到的,您必须使用.belongsToMany(Model).through(AnotherModel)
. 然后只需根据需要使用attach()
、detach()
和方法来处理数据updatePivot()
。withPivot()
此外,由于您正在定义连接模型,您还可以直接使用它来访问和修改相关表包含的数据。例如:
Appointment.forge({patient_id: 2, doctor_id: 1, confirmed: true}).save()
或者
Appointment.forge({id: 4}).destroy()
推荐阅读
- java - 类变量作为消息占位符,动态识别名称并替换其值
- flutter - 请帮助我理解这些代码行(什么意思? max() 是什么意思)
- reactjs - React - 如何使用 useState 在对象中推送数组
- python - 你如何获得稀疏张量中使用的张量的名称?
- javascript - 纯色背景生成器不会显示任何背景
- python - Flask Wtforms验证错误 - 为什么在检测到错误时提交表单
- python - 在 python 中有“期望一个缩进块”
- javascript - 删除reactjs中的重复项后如何从状态值和setstate创建数组
- python - 如何使用烧瓶登录处理角色
- google-cloud-firestore - 2FA 的 Firestore 安全规则