我有两个模型 Company
和 CompanyAdmin
。一个模型公司有很多公司管理员。我正在尝试在删除母公司时删除 CompanyAdmins,使用书架插件 bookshelf-cascade-delete
。我还使用 knex 连接 mysql 数据库。
这是我的模型:
const db = bookshelf(connection);
db.plugin(cascadeDelete);
const Company = db.Model.extend({
tableName: 'company',
idAttribute: 'id',
hasTimestamps: true,
company_admins: function () { return this.hasMany(CompanyAdmin); }, // console.log(this);
}, {
dependents: ['company_admins'],
});
const CompanyAdmin = db.Model.extend({
tableName: 'company_admin',
idAttribute: 'id',
hasTimestamps: true,
company: function () { return this.belongsTo(Company) },
});
当我在 company_admins 函数中 console.log(this) 时,我得到了这个数据:
ModelBase {
tableName: 'company',
idAttribute: 'id',
hasTimestamps: true,
company_admins: [Function: company_admins] }
这是我的 DELETE 路由处理程序:
.delete((req, res) => {
if (req.user) {
Company.forge({
id: req.user.attributes.company_id,
})
.destroy()
.then(() => {
res.status(200)
.json({
status: 200,
error: false,
});
req.logout();
}).catch((err) => {
console.log(err);
res.status(500)
.json({
status: 500,
error: err.message,
});
});
} else {
res.status(401)
.json({
status: 401,
message: 'User not authenticated',
});
}
});
我收到这个错误:
TypeError: Cannot read property 'hasMany' of undefined
有人遇到同样的问题吗?
最佳答案
我解决了这个问题。导入书架时出错。 我之前使用的代码是:
import bookshelf from 'bookshelf';
const db = bookshelf(connection);
正确的 bookshelf 导入是这样的:
const db = require('bookshelf')(connection);
不太清楚为什么以前的代码不起作用,但修改后的版本运行良好!
关于mysql - 书架级联删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42079199/