mysql - 在连接表中插入附加数据

标签 mysql node.js express knex.js bookshelf.js

我正在使用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'
                        })
                    })
            })

    })

“产品因素”表

|ID|product_id|factor_id|quantity|
|--|----------|---------|--------|
|1 |10        |3        |NULL    |
|2 |10        |5        |NULL    |

如何在附加关系的同时插入数量?

最佳答案

文档 the model.belongsToMany() section 中有一个如何执行此操作的示例。为了方便起见,这里是:

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);
  }
});

正如您在 DoctorPatient 模型中看到的,您必须使用 .belongsToMany(Model).through(AnotherModel)。那么只需使用 attach() 即可, detach() , updatePivot()withPivot()根据需要处理数据的方法。

此外,由于您正在定义连接模型,因此您还可以直接使用它来访问和修改相关表包含的数据。例如:

Appointment.forge({patient_id: 2, doctor_id: 1, confirmed: true}).save()

Appointment.forge({id: 4}).destroy()

关于mysql - 在连接表中插入附加数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50247170/

相关文章:

PHP:无法使用 PDO 插入到 MYSQL 表中

php - MYSQL SELECT FROM 两个表并减少查询

mysql - super /父 SQL 表上的索引

Javascript 函数调用给出了意想不到的奇怪结果。

arrays - 在 Node.js 中对数组中的相似字符串进行分组

node.js - Nodejs Express : Routes in separate files

MySQL 将行转为动态数量的列

javascript - 类型错误 :Cannot read property 'id' of undefined - nodejs - Sequlize

node.js - 使用 Typescript 扩展快速响应对象的正确方法

node.js - Express 中间件无法捕获 async/await 抛出的错误,但为什么呢?